面向对象总结1
一.创建和初始化对象
1.类与对象
类 是一种抽象的数据类型,它是某一类事物的整体描述或定义,但是并不能代表某一个具体的事物。
对象 是抽象概念的具体实例。
2.创建和初始化对象
使用new关键字创建对象
比如: People people = new People();
在创建的时候,除了分配内存空间之外,还会给创建好的对象进行默认的的初始化以及对类中构造器的调用
其过程为 :
注意:类作为模板,由属性和方法构成。属性不能初始化,创建对象后默认初始化。对象是类的具体实例。
package com.lu.OOP1.createobject;
//1.0创建和初始化对象
//学生类
public class Student {
//属性 注意:这里的我的Test类为外部包,想要用对象直接调用属性要加public
public String name ;
public int age;
//方法
public void studyCase(){
System.out.println(this.name+"的学习情况");
//这里this指代当前这个类
}
}
package com.lu.OOP1;
import com.lu.OOP1.createobject.Student;
/*
一个程序只有一个主启动或测试类
不要在每个类在加入main()方法,每个项目应该只有一个main()方法
*/
public class Test {
public static void main(String[] args) {
//Student类是抽象的===>需要实例化===>(实例化后)返回一个student
// (比如xiaoMng,xiaoHong这样的对象,他们是Student类的具体实例)
Student xiaoMing = new Student();
Student xiaoHong = new Student();
xiaoMing.name = "小明";
xiaoMing.age = 15;
System.out.println(xiaoMing.name);
System.out.println(xiaoMing.age);
xiaoMing.studyCase();
xiaoHong.name = "小红";
xiaoHong.age = 12;
System.out.println(xiaoHong.name);
System.out.println(xiaoHong.age);
xiaoHong.studyCase();
}
}
二.类中的构造器
构造器的本质是一个方法
一个类即使什么都不写,也会默认存在构造器。在该类的反编译Class文件中可看见。
package com.lu.OOP1.construct;
public class people {
public static void main(String[] args) {
}
}
在用new关键字创建对象的时候,同时会对该类的构造器进行调用
构造器的特点:
1.名字和类名相同
2.没有返回值类型,也没有void
构造器的作用:
1.用来初始化属性
2.使用new关键字创建对象,本质是在调用构造器
注意:
- 构造器分为有参和无参,有参即方法的重载
- 如果只显示定义有参构造,无参构造就被干掉了,即不存在。(启动 People people = new People();就会报错)
- 显示有参定义后,如果想要使用无参构造,就显式定义一个无参构造(里面一般不写语句)
快捷键: Alt +insert 快速创建构造器
关于用new关键字调用构造器的代码如下:
package com.lu.OOP1.construct;
public class Person {
String name;//null
int age;
int height ;//0
public Person(){
//this.name = "luxun";---一般显示定义出来,不写语句
}
public Person(String name){ //有参构造 初始化属性
this.name = name;
}
public Person(String name,int height){
this.name = name;
this.height = height;
}
}
package com.lu.OOP1.construct;
/*
一个程序只有一个主启动或测试类
不要在每个类在加入main()方法,每个项目应该只有一个main()方法
*/
public class Application {
public static void main(String[] args) {
Person person = new Person("卢逊",150);
System.out.println(person.name);
System.out.println(person.height);
}
}