类与对象的创建

类与对象的创建

概念

类:一种抽象的数据类型,它是对一类事物的整体描述、定义,但是并不能代表某一个具体的事务

对象:抽象概念的具体实例

创建与初始化对象

  1. 使用new关键字创建对象

  2. 使用new关键字创建的时候,除了分配内存空间外,还会给创建好的对象进行默认初始化 以及对类中构造器的调用

  3. 类中构造器也称为构造方法,是在进行创建的时候调用的。并且构造器有以下两个特点

    1.必须和类的名字相同

    2.必须没有返回类型,也不能写void

  4. 构造器很重要,必须要掌握

注:

类中无显式的构造器,会默认创建无参构造器,一旦有显式的有参构造器,必须显示创建有参构造器

package com.example.oop.demo02;

public class Student {
    String name;
    String age;

    public Student() {
    }

    public Student(String name) {
        this.name = name;
    }
}

package com.example.oop.demo02;

public class Application {
    // 一个工程只有一个main方法
    public static void main(String[] args) {
        Student xiaoMing = new Student();
        System.out.println(xiaoMing.name); // null
        xiaoMing.name = "小明";
        System.out.println(xiaoMing.name); // 小明

        Student xiaoHong = new Student("小红");
        System.out.println(xiaoHong.name); // 小红
    }
}
posted @ 2021-10-30 11:26  Oh,mydream!  阅读(31)  评论(0编辑  收藏  举报