instanceof 关键词
(类型转换)引用类型 判断一个对象是什么类型
System.out.println(x instanceof y); 能不能编译通过:x 和 y之间是否存在父子关系,即x 指向的实际类型是否是 y 的子类型
// parent
public class Person {
public void run(){
System.out.println("run");
}
}
// child
public class Student extends Person{
}
// child
public class Teacher extends Person{
}
// main()
public class Application {
public static void main(String[] args) {
// 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); // 编译报错
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); // 编译报错
}
}
引用类型的强制转换
- 父类引用指向子类的对象
- 把子类转换为父类,向上转型
- 把父类转换为子类,向下转型;强制转换
- 方便方法调用,减少重复的代码,提高代码利用率
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();
// 子类转换为父类,可能丢失自己本来的一些方法
Student s = new Student();
student.go();
Person person = student; // student转为person类型 低->高 直接转
}
}
static 修饰符
// static
public class Student {
private static int age; // 静态的变量
private double score; // 非静态的变量
public void run(){
}
public static void go(){
}
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);
// System.out.println(Student.score); 报错
System.out.println(s1.age);
System.out.println(s1.score);
// Student().run(); 报错
new Student().run();
Student.go();
}
}
非静态方法中可以直接调用静态方法
但在静态方法中,需要先new一个类的对象,才能调用非静态方法
静态代码块
//静态代码块
public class Person {
{
// 代码块 (匿名代码块)
}
static {
// 静态代码块 (匿名代码块
}
}
//静态代码块
public class Person {
// 2. 第二个执行,可用于赋初始值
{
System.out.println("匿名代码块");
}
// 1. 最早执行的 与类一起加载,只执行一次
static {
System.out.println("静态代码块");
}
public Person() {
System.out.println("构造方法");
}
// 3. 最后执行
public static void main(String[] args) {
Person person = new Person();
}
}
output
静态代码块
匿名代码块
构造方法
// 静态导入包
import static java.lang.Math.random;
public class Test {
public static void main(String[] args) {
System.out.println(random());
}
}
final
final修饰的类不可以再被继承