Home  >  Article  >  Java  >  How to define a class in java

How to define a class in java

angryTom
angryTomOriginal
2019-11-12 14:38:2612559browse

How to define a class in java

How to define a class in java

Member variables: attributes corresponding to things

Member methods : Corresponding to the behavior of things

Format of class definition

public class ClassName{
// 成员变量
// 成员方法
}

Define a class: It is to define the members of the class, including member variables and member methods (Recommended tutorial: java tutorial )

Member variables: It is almost the same as defining variables before. Only the location has changed. In the class, outside the method.

Member method: It is almost the same as the previously defined method. Just remove static, the role of static is in object-oriented

Example of class definition format

public class Person {
    //定义成员变量
    private String name;//姓名
    private int age;//年龄
    private char gendar;//性别
    //定义成员方法
    /**
     * study方法
     *
     */
    public void study(){
        System.out.println("好好学学习,天天向上");
    }
    /**
     * sleep();睡觉
     */
    public void sleep(){
        System.out.println("学习一天了,可以睡觉了");
    }
}

Class in Java

Classes can be seen as templates for creating Java objects. It is a collection of entities with certain common characteristics. It is an abstract data type. It is an abstraction of entities with the same characteristics. In object-oriented programming languages, a class is an abstraction of the properties and behavior of a type of "thing".

Give an example to illustrate the following category. For example, Person (person) is a category, then a specific person "Zhang San" is the object of the "human" category, and "name, height, weight" and other information They are the attributes of the object, and human actions such as "eating, getting dressed," etc. are the methods of the object. In short, a class is a collection of things with the same characteristics, and an object is a specific instance of the class. At the same time, classes have polymorphism and inheritance. For example, "human beings" can be divided into "men, women", "elderly people, children", then "men, women" are subclasses of "human beings" and so on.

The above is the detailed content of How to define a class in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn