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

How to define a class in java

angryTom
Release: 2019-11-12 14:38:26
Original
12605 people have browsed it

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{
// 成员变量
// 成员方法
}
Copy after login

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("学习一天了,可以睡觉了");
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template