首页 > 编程语言 >java学习笔记39

java学习笔记39

时间:2022-10-19 13:55:27浏览次数:41  
标签:instanceof 39 java System 笔记 Person Student println out

面向对象

instanceof和类型转换

instanceof

public class Application {
   public static void main(String[] args) {
       //System.out.println(x instanceof y);//能不能编译通过!

       //Object > Person > Student
       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);//Object > Person > Teacher   false
       System.out.println(object instanceof String);//false   Object > String
       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);//编译报错
  }
}


//子类
package oopzong.oop.opp5;

public class Teacher extends Person {

}
//子类
package oopzong.oop.opp5;

public class Student extends Person {

}
//父类
package oopzong.oop.opp5;

public class Person {
 
}

多态的类型转化

强制转换 高转低

//父类
package oopzong.oop.opp5;
public class Person {
   
}
//子类
package oopzong.oop.opp5;
public class Student extends Person {
   public void go(){
       System.out.println("go");
  }
}
//。。。。。
package oopzong.oop.opp5;

public class Application {
   public static void main(String[] args) {
       //类型之间的转化: 父类 子类
       //高               低   低转高自然转换
       Person per = new Student();
       //per.go();//无法运行 Person类没有go方法
       //将per这个对象转换为Student类型,就可以使用Student类型的方法了!
       //子类类型 变量名=(子类类型) 父类类型的变量;强制转换
       Student stu = (Student) per;
       stu.go();//((Student)per).go()
  }
}

低转高

//父类
package oopzong.oop.opp5;
public class Person {
   
}
//子类
package oopzong.oop.opp5;
public class Student extends Person {
   public void go(){
       System.out.println("go");
  }
}
//。。。。。。
public class Application {
   public static void main(String[] args) {
       //类型之间的转化: 父类 子类
       
       //子类转换为父类,可能丢失自己本来的一些方法
       Student stu = new Student();
       stu.go();
       Person per = stu;
       //per.go();无法运行

  }
}

总结

1.只能父类引用指向子类对象

2.把子类转换为父类,向上转型;

3.把父类转换为子类,向下转型;强制转换;

4.转换方便方法的调用,减少重复的代码

封装 , 继承 ,多态

标签:instanceof,39,java,System,笔记,Person,Student,println,out
From: https://www.cnblogs.com/12345ssdlh/p/16805974.html

相关文章