关于 instanceof

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于 instanceof相关的知识,希望对你有一定的参考价值。

先把程序发出来 class Person String name; String location; Person(String name) this.name = name; this.location = "beijing"; Person(String name,String location) this.name = name; this.location = location; public void getInfo() System.out.println("name:" + "_name" + "\n" + "location=" + location); public boolean equals(Object obj) if (obj == null) return false; if (obj instanceof Person) Person p = (Person)obj; if (p.name == this.name) return true; else return false; else return false; public String toString() return ("of Person"); class Teacher extends Person String title; Teacher(String name,String location,String title) super(name,location); this.title = title; Teacher(String name,String location) this(name,location,"Empty"); Teacher(String name) this(name,"Empty","Empty"); public void getInfo() System.out.println("name:" + name + "\n" + "location:" + location + "\n" + "title:" + title); class Student extends Person String school; Student(String _name) this(_name,"beijing","qinghua"); Student(String _name,String _location) this(_name,_location,"qinghua"); Student(String _name,String _location,String _school) super(_name,_location); this.school = _school; public void getInfo() System.out.println("name:" + name + "\n" + "location:" + location + "\n" + "school:" + school); public String toString() return ("of Student"); public boolean equals(Object obj) //这句编译是通过的 即使我输入一个Dog类的实例 他也可以运行 返回一个false的值 问题在下面 往下看 对比 if (obj == null) return false; if (obj instanceof Student) Student s = (Student)obj; if (s.school == school) return true; else return false; else return false; class Dog2 ; public class TestM public static void main(String args[]) Student yuhean = new Student("JiangChao1","湖州","university of Ningbogongcheng"); yuhean.getInfo(); Teacher JiangChao = new Teacher("JiangChao","Ningbo","Professor"); JiangChao.getInfo(); Dog2 d = new Dog2(); System.out.println(yuhean.toString() + "\n" + JiangChao); System.out.println(yuhean.equals(d)); //问题在这里开始 if (d instanceof Person) //对比上面我备注的那句句子 这句在编译时出错 显示 不可转换的类型 这里我故意将d这个对象设置成了Dog类中的实例,但是编译是不通过的 而在上面的语句中 即使我传入了一个Dog类的对象 仍然会返回一个false 但这里应该返回false 却显示编译出错 System.out.println(true); else System.out.println(false);

参考技术A 例子没错,e
instanceof
mangaer为真的话,e就是manager的一个实例,当然可以那样转换。
后面一个,编译能通过,但是如果转换出错会在运行时报错。

以上是关于关于 instanceof的主要内容,如果未能解决你的问题,请参考以下文章

小知识(h5 js )

Java中关键字总结汇总

教妹学Java:判断对象的类型,instanceof关键字

instanceof,Object.getPrototypeOf(),Object.create(),Object.setPrototypeOf(),Object.prototype.isProtot

js万能类型检测Object.prototype.toString.call——定制Object.prototype.toString.call的检测结果

再聊面试,这次关于钱,关于培训,关于内卷