类和对象的关系
类与对象的关系
类是一种抽象的数据类型,是对某一类事物整体的描述或定义,但是不能代表某一个具体的事物
对象是抽象概念的具体实例
例如下文的student,xiaoming,xiaohong就是对Student的实例化后的具体对象
创建与初始化对象
使用new关键字创建的时候,除了分配内存空间之外,还会给创建好的对象,进行默认的初始化操以及对类中构造器的使用
字符串的默认值是null,整型变量的默认值是0
package com.wtnever.opp.demo02;
//一个项目应当只有一个main方法
public class Application {
public static void main(String[] args) {
//类,抽象的,实例化
//类实例化后会返回一个自己的对象
//student对象就是一个Student类的具体实例
Student student = new Student();
//就是一个具体的实例小明,小红
Student xiaoming = new Student();
Student xiaohong = new Student();
/*Student提供的是一个空模板,小明和小红是具体的学生对象
未赋值前,具体的对象里里面的属性为默认值
*/
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
System.out.println(xiaoming.high);
xiaohong.name = "基金韭菜王";
xiaohong.age = 22;
xiaohong.high = 174.5;
System.out.println(xiaohong.name);
System.out.println(xiaohong.age);
System.out.println(xiaohong.high);
}
}
package com.wtnever.opp.demo02;
public class Student {
//
String name;
int age;
double high;
//方法
public void study(){
//this代表指向当前的类
System.out.println(this.name+"在学习");
}
}

浙公网安备 33010602011771号