大家好,今天给大家分享一下Java类和对象的创建
类数一种抽象的数据结构,它是对某一类事物整体定义和描述,但是并不能代表某一个具体的事物
例如,
动物,植物,手机,计算机 (都是类,它是对某一类事物整体定义和描述)
Person类,Pet类,Car类等,这些类都是用来描述、定义某一种事物应该具备的特点和行为
对象是抽象的具体实例
张三,这个人,就是person(人)这一类当中的一个具体实例
张三家里的旺财就是狗的一个具体实例
可以体现出特点,展现出功能的具体的实例,就叫做对象,而不是一个抽象的概念,并且构造器有两个特点
1.必须和类的名字相同
2.必须没有返回类型,也不能写void
创建和初始化对象
使用new 关键字创建对象,除了分配内存空间以外,还会给创建好的对象进行初始化以及对类中构造器的调用
类中的构造器也称为构造方法,是在进行创建对象的时候必须要调用的。
代码实例
package Lei;
//一个项目应该只有一个main方法
public class student {
public static void main(String[] args) {
}
}
示例
package Lei;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
}
}
整体截图
在student 文件当中写代码
package Lei;
//student 类
public class student {
//属性:字段
String name; //默认为null
int age; //默认为0
//方法
public void study(){
System.out.println(this.name+"在学习");
}
}
在Application文件当中写代码:
package Lei;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
//类: 抽象的,实例化
//类实例化之后回复回一个自己的对象
// student 对象(第二个)是student类(第一个)的具体实例
student student=new student();
//第一个student代表的是学生这个统称,是一个类
//第二个student 代表的是一个具体的实例,是一个对象
student xiaoming =new student();
student xiaofei =new student();
// xiaoming xiaofei 是一个对象
System.out.println(xiaoming.name);
}
}
仔细看注释,写的已经很清楚了
看代码执行效果
package Lei;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
//类: 抽象的,实例化
//类实例化之后回复回一个自己的对象
// student 对象(第二个)是student类(第一个)的具体实例
student student=new student();
//第一个student代表的是学生这个统称,是一个类
//第二个student 代表的是一个具体的实例,是一个对象
student xiaoming =new student();
student xiaofei =new student();
// xiaoming xiaofei 是一个对象
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
}
}
显示结果
结果是这样的,是因为我们没有给对象赋值
所以最后的结果是默认值
注释写的很清楚
给小明这个对象赋值
我们定义名字和年龄
package Lei;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
//类: 抽象的,实例化
//类实例化之后回复回一个自己的对象
// student 对象(第二个)是student类(第一个)的具体实例
student student=new student();
//第一个student代表的是学生这个统称,是一个类
//第二个student 代表的是一个具体的实例,是一个对象
student xiaoming =new student();
student xiaofei =new student();
// xiaoming xiaofei 是一个对象
xiaoming .name="小明";
xiaoming.age= 3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
}
}
跑一下程序,看一下执行结果
结果正常
下面,给xiaofei 也赋值
package Lei;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
//类: 抽象的,实例化
//类实例化之后回复回一个自己的对象
// student 对象(第二个)是student类(第一个)的具体实例
student student=new student();
//第一个student代表的是学生这个统称,是一个类
//第二个student 代表的是一个具体的实例,是一个对象
student xiaoming =new student();
student xiaofei =new student();
// xiaoming xiaofei 是一个对象
xiaoming .name="小明";
xiaoming.age= 3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
xiaofei.name="小菲";
xiaofei.age=3;
System.out.println(xiaofei.name);
System.out.println(xiaofei.age);
}
}
我们来看一下执行结果
结果正常
好了,上面的注释写的非常清晰了,我们主要是使用new关键词来创建对象
有关于Java类和对象的创建就到这里了,谢谢大家