一、引用类型的转换
- 子类转换为父类可能会丢失自己本来的一些方法
- 父类引用指向子类对象
- 把子类转换为父类,向上转型
- 把父类转换为子类,向下转型(强制转换)
person类
public class Person {
void run(){
System.out.println("run");
}
}
student类
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
测试类
public class Application {
public static void main(String[] args) {
//类型之间的转换:父 子
//高 //低
Person obj=new Student();
//obj不可以调用go方法,编译看左边
//student 将这个对象强转为Student类型,我们就可以使用Student类型的方法
// Student student=(Student)obj;
// student.go();
((Student)obj).go();//前两行代码的合成
//将obj强转为Student类型,就可以调用go方法。
}
}
二、instanceof关键字
- System.out.println(x instanceof Y);
- 能不能编译通过看x和y是否存在父子关系
Person类
注:代码中Student类与Teacher分别是Person的子类
public class Application {
public static void main(String[] args) {
//System.out.println(x instanceof Y);//能不能编译通过!x和y是否存在父子关系,
Object object=new Student();
//Object>String
//Object>Person>teacher
//Object>Person>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);
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);//false
//编译错误 System.out.println(student instanceof String);//false
}
}
三、static关键字
public class Student {
private static int age;//静态变量 多线程
private double score;//非静态变量
public void run(){
System.out.println();
go();//非静态方法可直接调用静态方法,静态方法随类一起加载
}
public static void go(){
System.out.println();
//静态方法可以调用静态方法,但不可以调用非静态方法。
}
public static void main(String[] args) {
Student s1=new Student();
System.out.println(Student.age);//可用类名直接调用
System.out.println(s1.age);
System.out.println(s1.score);
s1.run();
Student.go();//直接调用方法
}
}
四、代码块
public class Person {
{
System.out.println("匿名代码块");//2.第二个执行
/*
匿名代码块的作用:赋初始值
*/
}
static{
System.out.println("静态代码块");//1.最早执行,与类一起加载,只执行一次
}
public Person(){
System.out.println("构造方法");//3.第三个执行
}
public static void main(String[] args) {
Person person1=new Person();
System.out.println("===================");
Person person2=new Person();
}
}
运行结果
静态代码块
匿名代码块
构造方法
===================
匿名代码块
构造方法
五、导入静态包
package com.oop.demo07;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(random());
}
}