前面说过类和对对象的关系
类是对象的抽象模板,对象是类的具体实例。
所以代码中,先要创建类,然后再以类为模板,新建对象。
举例:
例1.
Student xiaohong = new Student();
//新建1个对象,对象名叫xiaohong,对象是以类Student为模板的
例2:
Student xh= new Student();
//新建1个对象,对象名叫xh,对象是以类Student为模板的
新建对象的语法:
类 对象名 = new 类()
例3:新建小明和小红的具体对象
package oop;
//新建抽象的类Student
public class Student {
// 属性:字段
String name;//初始值
int age;//初始值
public void study(){//扩展部分
System.out.println(this.name + "在学习");
}
}
以下是具体对象运行的代码
package oop;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
Student xiaoming = new Student();
Student xiaohong = new Student();
xiaoming.name = "小明";
xiaoming.age = 3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
System.out.println(xiaohong.name);
System.out.println(xiaohong.age);
xiaohong.study();
xiaoming.study();
}
}
打印结果
小明
3
null
0
null在学习
小明在学习
Process finished with exit code 0```