java第九天(多态相关知识、子父类类型转换、instanceof判断继承关系、static静态详解)
多态相关知识
转型
向上转型:子类转换为父类,可能会丢失自己本来的方法
向下转型:父类转换为子类,使父类可以使用子类特有的方法,需要强制类型转换
子类 实例化子类名=(子类)需要转换的实例化父类名
或者
((子类)需要转换的实例化父类名).子类方法;

instanceof
判断一个对象与类是否有继承关系

语法:
Person person = new Student();
System.out.println(person instanceof Object);
System.out.println(person instanceof Person);
System.out.println(person instanceof Student);
System.out.println(person instanceof Teacher);
编译看左边,Person与那些都有关系,所以能编译
运行看右边,Student与Teacher没有继承关系,所以报错
static 静态
变量
非静态变量需要先将类实例化成对象,然后通过对象名.变量名使用
静态变量可以直接通过类名.变量名使用
public class Student {
private static int age=10;//静态变量
private double score=90;//非静态变量
public static void main(String[] args) {
Student s1 = new Student();//实例化对象
System.out.println(s1.score);//对象名.变量名
System.out.println(s1.age);//对象名.变量名
System.out.println(Student.age);//类名.变量名
System.out.println(Student.score);//类名.变量名(报错)
}
}
方法
静态方法跟类一起加载,所以静态方法无法直接调用非静态方法,因为静态方法加载时,非静态方法还没加载。但是非静态方法可以直接调用静态方法。(静态方法也可以调用静态方法)
- 静态方法和非静态方法都可以通过实例化对象使用(对象名.方法名();)
- 静态方法在本类可以直接使用,非静态方法不行(方法名();)
- 静态方法可以通过类名使用,非静态方法不行(类名.方法名();)
public static void run() {
System.out.println("静态方法run被调用");
}
public void go() {
System.out.println("非静态方法go被调用");
}
public static void main(String[] args) {
Student student = new Student();
student.go();//通过实例化对象使用
student.run();//通过实例化对象使用
run();//直接使用
go();//无法直接使用(报错)
Student.run();//通过类名使用
Student.go();//无法通过类名使用(报错)
}
代码块
代码块是用大括号括起来的,静态代码块只执行一次
顺序:静态代码块最先执行,然后执行代码块,再执行构造方法
public class Student {
{
System.out.println("这是非静态代码块");
}
static {
System.out.println("这是静态代码块");
}
public Student() {
System.out.println("这是构造器");
}
public static void main(String[] args) {
Student student1 = new Student();
System.out.println("========================");
Student student2 = new Student();
}
}

静态导入包
静态导入包或者方法后,可以直接使用,不需要类名.方法名
语法:
import static java.lang.Math.PI;
抽象类(抽象的抽象--约束)
通过abstract修饰
抽象方法只有方法名字,没有方法的实现
- 抽象类不能new出来,只能通过子类去实现它
- 抽象类可以写普通方法
- 抽象方法必须写在抽象类里面

浙公网安备 33010602011771号