JAVA road day06

Object-Oriented

1. The essence is to organize a class code to objects encapsulate data
2. Abstract
3. three properties: encapsulation, inheritance, polymorphism
4. The class attributes and methods which have

Create a class

/*
创建一个类,用对象来封装数据。相当于数据结构体。
类中只有静态的数据和动态的方法
 */
public class Student {
    String name;
    int age;
    public void speak(){
        System.out.println("I am "+this.name+",I am "+this.age+" years old!");
    }
}
/*
public class Application {
    public static void main(String[] args) {
        Student s1=new Student();//用new关键字创建对象,此时分配空间,进行初始化
        Student s2=new Student();
        s1.name="Yang shengjie";
        s1.age=21;
        s2.age=18;
        s2.name="Xie jiayu";
        s1.speak();
        s2.speak();
    }
}
 */

Constructor

/*
构造器
1.一个类里面即使什么都不写,也存在一个和类同名的方法
2.使用new关键字,必须有构造器,本质就是调用构造器
3.作用就是实例化初始值
4.可以定义不同的有参构造器,相当于重载构造器
5.快捷键:alt+insert。可以自动生成构造器
6.构造器名必须和类名相同
 */

public class Constructor {
    String name;
    int age;
    int height;
    //显示的定义构造器
    //无参构造器
    public Constructor(){}
    //有参构造器
    //如果定义有参构造器,则必须显示的定义无参构造器
    public Constructor(String name){
        this.name=name;
    }
    public Constructor(String name,int age){
        this.name=name;
        this.age=age;
    }
    public Constructor(String name,int age,int height){
        this.name=name;
        this.age=age;
        this.height=height;
    }
}
/*
public class Application {
    public static void main(String[] args) {
        Constructor person1=new Constructor("yang");
        Constructor person2=new Constructor("yang",21);
        Constructor person3=new Constructor("yang",21,178);
        System.out.println(person1.name);
        System.out.println(person2.age);
        System.out.println(person3.height);

    }
}
 */

Here Insert Picture Description

Analysis: First class in the heap and static methods to allocate space, the main method is then pushed onto the stack, but also pushed onto the stack when the class variables stated, if the initialization data is allocated on the heap space constructor initializes data.

Published 14 original articles · won praise 0 · Views 208

Guess you like

Origin blog.csdn.net/YSJS99/article/details/105000212