How to define a class in Java
In Java, a class can be defined using the keyword “class”. The definition of a class usually includes the following parts:
- Access modifiers: Classes can use access modifiers to restrict other code’s access to the class. Commonly used access modifiers include “public”, “private” and “protected”.
- Class name: A class name should be a valid identifier according to Java naming conventions, starting with a capital letter and following the camel case naming convention.
- Class member variables: These are variables that describe the properties of a class. They can have different data types and can be accessed and modified by methods of other classes.
- Methods of a class: Methods of a class are functions that describe the behavior of the class. They can have different access modifiers and may or may not have a return value.
Here is a simple example of a class definition:
public class MyClass {
private int myVariable;
public void setMyVariable(int value) {
myVariable = value;
}
public int getMyVariable() {
return myVariable;
}
}
In the above example, a class called “MyClass” is defined. This class includes a private member variable called “myVariable” and two public methods, “setMyVariable” and “getMyVariable,” used for setting and retrieving the value of the member variable.