类与对象的创建

113 阅读1分钟
  1. 类的创建 一个类里面有两种东西:属性和方法
package com.oop.demo2;

//学生类
public class Student {

    //属性:字段
    String name;
    int age;

    //方法
    public void study(){
        System.out.println(this.name+"\tis studying now");
    }

    public void sayAge(){
        System.out.println(this.name+"\tis\t"+this.age+"years old!");
    }

}
  1. 对象的创建:在main方法里面创建
        //类:抽象的,实例化的
        //类实例化后会返回一个自己的对象!
        //student对象就是一个Student类的具体实例

        Student student1 = new Student();
        Student student2 = new Student();

        student1.name = "Marry";
        student1.age = 23;

        student2.name = "Jane";
        student2.age = 22;

        student1.study();
        student1.sayAge();

        student2.study();
        student2.sayAge();