面向对象
构造函数内调用构造函数
- 一般运用在设置默认值
- 要放在构造函数方法体内的第一行
class Student {
String name;
public Student(String name) {
this.name = name;
}
public Student() {
this("张三"); //this 关键字调用自身有参构造函数, 只能在第一行
}
}
继承
子类无法直接访问父类的私有方法和属性
public class Main {
public static void main(String[] args) {
UniStudent s1 = new UniStudent("张三");
s1.name = "李四"; // 这行代码是出错的, 提示父类的 name 字段是私有的
}
}
class Student {
private String name;
public Student(String name) {
this.name = name;
}
}
class UniStudent extends Student {
public UniStudent(String name) {
super(name);
}
}
子类必须调用一次父类的构造函数
- 如果子类和父类都没有重载构造函数, 意味着只存在默认的构造函数, 此时子类的构造函数不用做处理.
- 假如父类构造函数为有参构造函数, 且没有写无参构造函数. 这意味着, 默认的无参不再存在, 此时父类没有无参构造函数. 这时候子类的构造函数必须要利用
super
关键字调用父类的有参构造函数.
class Student {
//父类没有定义无参构造函数
public Student( int a) {
}
}
class UniStudent extends Student {
public UniStudent(int a) {
super(a); //super 关键字直接调用父类有参构造方法
}
}
多态
自动转型(向上转型)
-
通过子类构造函数创建父类对象:
B extends A
»A a = new B()
-
方法调用顺序
- 先找父类方法, 如过父类方法被子类重写, 就要调用子类的重写方法
package com.company;
public class Main {
public static void main(String[] args) {
Student s1 = new UniStudent("张三");
s1.Study(); // 输出子类重写的 Study 方法: UniStudent studies
}
}
class Student {
private String name;
public Student(String name) {
this.name = name;
}
public Student() {
this("张三");
}
public void Study() {
System.out.println("Student studies");
}
}
class UniStudent extends Student {
public UniStudent(String name) {
super(name);
}
public void Study() {
System.out.println("UniStudent studies");
}
public void reserch() {
System.out.println("UniStudent reserches");
}
}
强制转型(向下转型)
- 强制转型的前提是, 当前对象是通过向上转型创建的. 否则, 运行时会出现
ClassCastException
的错误.
package com.company;
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
UniStudent s2 = (UniStudent) s1;// 此行会报错
s2.reserch();
//以下是正确代码
Student s1 = new UniStudent("张三");
UniStudent s2 = (UniStudent) s1;
s2.reserch();
}
}
class Student {
private String name;
public Student(String name) {
this.name = name;
}
public Student() {
this("张三");
}
public void Study() {
System.out.println("Student studies");
}
}
class UniStudent extends Student {
public UniStudent(String name) {
super(name);
}
public void Study() {
System.out.println("UniStudent studies");
}
public void reserch() {
System.out.println("UniStudent reserches");
}
}