How can classes be defined in Java?

In Java, a class can be defined using the keyword “class”. The typical format for defining a class is as follows:

访问修饰符 class 类名 {
    // 类的成员变量(属性)

    // 类的构造方法

    // 类的成员方法
}
  1. Access modifier: indicates the class’s access permissions, which can be public, protected, private, or omitted.
  2. “Class: a keyword used to declare a class.”
  3. Class name: Represents the name of the class, according to naming conventions, the class name should be in PascalCase (capitalize the first letter).
  4. Class member variables: represent the attributes or fields of the class, i.e. the data members of the class.
  5. Constructor of a class: a method with the same name as the class after the keyword “class” is used to create objects of the class.
  6. Class member methods: represents the methods of a class, which are the behavioral members of the class.

Here is an example code demonstrating the definition of a simple Java class.

public class MyClass {
    // 类的成员变量
    private int num;

    // 类的构造方法
    public MyClass() {
        num = 0;
    }

    // 类的成员方法
    public void setNum(int value) {
        num = value;
    }

    public int getNum() {
        return num;
    }
}

In the given example, MyClass is a public class that consists of a private integer member variable num, a public parameterless constructor, and two public member methods setNum and getNum.

Leave a Reply 0

Your email address will not be published. Required fields are marked *