java中instanceof 和 子类父类之间的转换
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java中instanceof 和 子类父类之间的转换,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2507字,纯文字阅读大概需要4分钟。
内容图文
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 和 子类父类之间的转换全部内容,希望文章能够帮你解决java中instanceof 和 子类父类之间的转换所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。