(1).类与对象的关系
-
类是个抽象的数据类型,它是对某一类事物的整体描述、定义,但是并不是代表某一个具体的事物;
-
动物、植物、手机、电脑……
-
Person类、Pet类、Car类等,这些类都是用来描述、定义某一类具体的事物应该具备的特点和行为;
-
-
对象是抽象概念的具体实例
-
张三就是人的具体实例,张三家里的旺财就是狗的一个具体实例;
-
能够体现出特点,展现出功能的是具体的实例,而不是抽象的概念。
-
public class Student {
//属性:字段
String name;
int age;
//方法
public void study(){
System.out.println(this.name+"在读书!");
}
}
public class Demo01 {
public static void main(String[] args) {
Student student = new Student();
student.study();
}
}
(2).创建和初始化对象
-
使用new 关键字创建对象;
//学生类
public class Student {
//属性:字段
String name; // 默认为:null
int age; // 默认为:0
//方法
public void study(){
System.out.println(this.name+"在读书!");
}
}
//项目中应该只存一个main方法
public class Demo01 {
public static void main(String[] args) {
//类:抽象类,实例化
//类实例化后会返回一个自己的对象
//student对象是一个Student的具体实例!
Student xiaoming = new Student();
Student xiaohong = new Student();
xiaoming.name = "小明";
xiaoming.age = 18;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
xiaoming.study();
xiaohong.name = "小红";
xiaohong.age = 18;
System.out.println(xiaohong.name);
System.out.println(xiaohong.age);
xiaohong.study();
}
}



