首页 > 编程语言 > 详细

java中instanceof 和 子类父类之间的转换

时间:2021-03-16 22:27:57      阅读:95      评论:0      收藏:0      [点我收藏+]

instanceof 判断两者是否有继承关系

调用类

package Demo04;
?
public class Application {
   public static void main(String[] args) {
       //instanceof 一条线的线性指向关系,在这条线的为true
       //主要与左边的类型有关,右边为指向关系
       //Object>Person>Student || Teacher
       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);//编译错误
       //Studnet 与 Teacher 为同类
       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
       //Person类引用指向为Student与Teacher无关
       System.out.println("=======================");
       Object object = new Student();
       System.out.println(object instanceof String);//false
       //Object>String || Person object应该是与Person有线性的关系
       System.out.println(object instanceof Person);//true
?
  }
}

父类

package Demo04;
?
public class Person {
?
}
?

 

子类

package Demo04;
?
public class Student extends Person {
?
}
?
package Demo04;
?
public class Teacher extends Person{
}
?

子类父类间的转换

子类转向父类自动转化 低转高自动

调用类

package Demo04;
?
public class Application {
   public static void main(String[] args) {
       //可以理解为student子类类自动转为父类Person类
       Person student = new Student();
  }
}
?

 

父类

package Demo04;
?
public class Person {
?
}
?

子类

package Demo04;
?
public class Student extends Person {
?
}

父类转化为子类需要强制转换 ,高转低强制

调用类

package Demo04;
?
public class Application {
   public static void main(String[] args) {
?
       Person person = new Student();
       //person.go();//报错子类的独有方法父类不能直接调用
       //通过强制转换的方式调用子类的方法
      ((Student) person).go();//go
       Student student = new Student();
       student.say();//say
       student.go();//go
       //子类不仅可以调用自己的方法还继承了父类的方法
  }
}
?

 

父类

package Demo04;
?
public class Person {
   public void say(){
       System.out.println("say");
  }
?
?
?
}
?

子类

package Demo04;
?
public class Student extends Person {
   //子类中定义了一个方法父类不能直接调用
 public void go(){
     System.out.println("go");
}
}
?

 

java中instanceof 和 子类父类之间的转换

原文:https://www.cnblogs.com/continue-student/p/14545251.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!