多态
父类的引用指向子类的对象
多态注意事项:
1. 多态是方法的多态,属性没有多态
2. 父类和子类,类型转换异常:ClassCastException!
3. 存在条件:继承,方法需要被重写,父类引用指向子类对象! Father f = new Son();
4. 不能被重写的方法类型:static、final、private
5. 被final修饰的类不能有子类
instanceof和强制转换
instanceof
一般先用instanceof判断对象的类,然后再进行强制转换
package InstanceofAndTypeconversion;
public class Application {
public static void main(String[] args) {
//instanceof 判断对象是否属于这个类
//Object > Person > Student
//Object > Person > Teacher
//Object > String
//这几条线列出来了就很好判断了
Object object = new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("====================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
//System.out.println(person instanceof String);
//编译的时候就报错了,person跟String没有联系
System.out.println("====================");
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);
//System.out.println(student instanceof String);
//同理,student与Teacher和String都没关系
}
}
class Person {
public void run(){
System.out.println("person-run");
}
}
class Student extends Person {}
class Teacher extends Person {}
强制转换
- 父类引用指向子类的对象
- 把子类转换成父类,向上转换
- 把父类转换成子类,强制转换
package InstanceofAndTypeconversion;
public class Application {
public static void main(String[] args) {
//强制转换:父类——>子类
Person person = new Student();
//person.go(); 报错:父类用不了子类独有的方法
Student student = (Student)person;//强制转换
student.go();//student-go
//子类——>父类,不是强转,但可能丢失自己本来的方法
Student student2 = new Student();
Person person2 = student2;
//person2.go(); 报错
((Student)person2).go();
}
}
class Person {
public void run(){
System.out.println("person-run");
}
}
class Student extends Person {
public void go(){
System.out.println("student-go");
}
}
static
1. 建议静态变量通过类名访问,非静态变量只能通过对象访问
2. 非静态方法可以调用静态方法;
3. 静态方法不可以调用非静态方法
原因:静态方法是与类一起加载的,非静态方法在new出对象后才加载的
4. 静态方法可以调用静态方法
5. 非静态方法只能通过对象访问;
代码块
1. 代码块是在构造器之前运行的
2. 静态代码块是与类一起加载的,而且只运行一次