A method in superclass works for all the subclasses in java....If a subclass has its own independent method, how can i make it work...
class Polymorphism3 {
public static void main(String[] args) {
// note how these are all considered objects of type Animal by Java
Animal[] a = new Animal[4];
a[0] = new Mouse();
a[1] = new Bird();
a[2] = new Horse();
a[3] = new Animal();
for (int i=0;i<4;i++) {
a[i].pullTail();
}
//...
class Animal {
public void pullTail() {
System.out.println("I don't know what to say.");
}
}
class Mouse extends Animal {
public void pullTail() {
System.out.println("fart");
}
}
class Bird extends Animal {
public void pullTail() {
System.out.println("tweet");
}
public void fly() {
System.out.println("flap");
}
}
class Horse extends Animal {
public void pullTail() {
System.out.println("neigh");
}
}
You can't make it work if it's not declared in Animal.
The only way is to cast Animal to Bird such as
((Bird)a[1]).fly();
You can also call it from Bird's implementation of putTail.
In case this is about not being able to instantiate the nested classes: you need an object of the enclosing class for that:
public class Polymorphism3 {
public static void main(String[] args) {
// note how these are all considered objects of type Animal by Java
Animal[] a = new Animal[4];
Polymorphism3 poly = new Polymorphism3();
a[0] = poly.new Mouse();
a[1] = poly.new Bird();
a[2] = poly.new Horse();
a[3] = poly.new Animal();
for (int i = 0; i < 4; i++) {
a[i].pullTail();
}
}
class Animal {
public void pullTail() {
System.out.println("I don't know what to say.");
}
}
class Mouse extends Animal {
public void pullTail() {
System.out.println("fart");
}
}
class Bird extends Animal {
public void pullTail() {
System.out.println("tweet");
}
public void fly() {
System.out.println("flap");
}
}
class Horse extends Animal {
public void pullTail() {
System.out.println("neigh");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.