To create a class in Java, you can use the following syntax:
public class MyClass {
// class body
}Sour:ecwww.lautturi.comHere, MyClass is the name of the class. The public keyword indicates that the class is visible to other classes in the same package, or to classes in other packages if the class is imported.
Inside the curly braces, you can define the fields (variables) and methods (functions) that belong to the class. For example:
public class MyClass {
// fields
private int x;
private String name;
// methods
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
In this example, MyClass has two private fields: x of type int and name of type String. It also has four methods: setX, getX, setName, and getName, which are used to set and get the values of the fields.
To create an instance (object) of the MyClass class, you can use the following code:
MyClass obj = new MyClass();
You can then use the methods of the object to set and get the values of the fields, like this:
obj.setX(10);
int x = obj.getX(); // x will be 10
obj.setName("John");
String name = obj.getName(); // name will be "John"