当你将变量声明为具有超类的类型时,只能通过该变量访问(公共)方法和超类的成员变量。
Pet cat = new Cat("Feline",12,"Orange"); cat.getName(); // this is OKcat.getColor(); // this is not OK, getColor() is not in Pet
要访问具体类中的方法(Cat在这种情况下),你需要将变量声明为派生类
Cat cat = new Cat("Feline",12,"Orange"); cat.getName(); // OK, getName() is part of Cat (and the superclass)cat.getColor(); // OK, getColor() is part of Cat
或将其转换为你知道/怀疑是具体类型的类型
Pet cat = new Cat("Feline",12,"Orange"); ((Cat)cat).getName(); // OK (same as above)((Cat)cat).getColor(); // now we are looking at cat through the glass of Cat
你甚至可以结合使用两种方法:
Pet pet = new Cat("Feline",12,"Orange"); Cat cat = (Cat)pet;cat.getName(); // OKcat.getColor(); // OK
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)