Home  >  Article  >  Java  >  Java object-oriented detailed introduction to classes and objects

Java object-oriented detailed introduction to classes and objects

黄舟
黄舟Original
2017-08-09 09:20:131621browse

What is a class? What is an object?
1) The real world is composed of many objects. Classes are extracted based on objects
2) Object: a real individual individual
Class: category/type, representing a type of individual
3) The class can contain:
3.1) Attributes/characteristics common to all objects----------Member variables
3.2) Behaviors common to all objects--------- ------Method
4) A class can create multiple objects of the same type, with the same structure and different data
5) A class is the template of an object, and the object is a specific instance of the class
2. How to create a class? How to create an object? How do I access members?

Create a class and express the common attributes of the abstracted object as member variables. When accessing member variables, create an instance object first, and use the instance object to access the members.
3. Draw an equal sign between reference types

The equal sign used by variables of reference types (encapsulated types, except basic types) points to the reference object. When an object is created, a space is created in the heap to place the object. Reference type variables create a space in the stack to save the address

and point to the instance object in the heap. (More abstract)
4.null and NullPointerException

The reference type defaults to null when it is declared. If used before creating an instance object, a NullPointerException will occur

public class student {
public static void main(String[] args) {
//创建一个学生对象
Student stu = new Student();
//访问成员变量

stu.name = "zhangsan";
stu.age = 25;
stu.address = "河北石家庄";
//调用方法
stu.study();
stu.sayHi();

Student ls = new Student();
ls.name = "lisi";
ls.age = 26;
ls.address = "天津";
ls.study();
ls.sayHi();

//创建一个学生对象
//给所有成员变量赋默认值
Student ww = new Student();
ww.study();
ww.sayHi();

}

}
class Student {
//成员变量
String name;
int age;
String address;
//方法
void study(){
System.out.println(name+"在学习...");
}
void sayHi(){
System.out.println("我叫"+name+",今年"+age+"岁了,家住"+address);
}
}

The above is the detailed content of Java object-oriented detailed introduction to classes and objects. 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