首页 > 技术文章 > static关键字总结

woziji 2021-10-26 10:31 原文

instanceof和类型转换

1.父类的引用指向子类对象
2.把子类转化为父类,向上转型
3.把父类转化为子类,向下转型,强制转换
4.方便方法的调用,减少重复的代码

instanceof

Object object=new Student();
       //Object>Person>Student
       //Object>Person>Teacher
       //Object>String
       //System.out.println(x instanceof Y);//能不能编译通过,就看存不存在父子关系
       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);

 

static关键字总结

  1. 静态代码块

    package com.oop.demo07;

    public class Person {
      {//2
           //(代码块)匿名代码块
           System.out.println("匿名代码块");
      }

       static {//1
           System.out.println("静态代码块");

      }

       public Person() {//3
           System.out.println("构造方法");
      }

       public static void main(String[] args) {
           Person person1 = new Person();
           System.out.println("===============================");
           Person person2 = new Person();

      }
    }
  1. 方法加了静态修饰,可以直接调用方法

    public class Student {
       /*private static int age;
       private double score;*/
       public static void go(){
           System.out.println("我们去吃饭");
      }
       public void run(){
           System.out.println("我在跑");
      }
       public static void main(String[] args) {
        /*   Student s1 = new Student();
           System.out.println(Student.age);
           System.out.println(s1.score);
           System.out.println(s1.age);*/
           go();
           Student.go();
           Student student=new Student();
           student.run();
           student.go();
      }
  1. 静态导入包

    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());
           System.out.println(PI);
      }
    }

推荐阅读