I'm not new to coding, but new to polymorphism/inheritance/etc. I'm confused about static/dynamic binding, and specifically what happens when I put different subclasses in an array together. I'm working with some very simple animal classes, and just trying to learn the basics.
I tried defining them as ligers too, but then when I tried to print the array of animals' sizes, they both had -1 as their size. The way I have it now gives p0 the right size, but not p1.
public abstract class Animal {
public int size = -1;
}
public class Tiger extends Animal {
}
public class Liger extends Animal {
public int size = 121;
}
public static void main(final String[] args) {
Animal[] animal = new Animal[10];
Animal p0 = new Liger();
p0.size = 11;
animals[0] = p0;
Animal p1 = new Liger();
animals[1] = p1;
}
When I define the ligers as animals, p1 gets -1 as its size instead of the 121 I want it to have. I'm sure the issue is with me calling it an Animal instead of a liger, but I'm not sure what the correct syntax is to fix it. I want them to be able to be in an array with tigers.
Please, what is fs in your line
Animal p1 = fs.new Liger();
By the way, take a look at this code and tell me if it does what you are looking for.
public static void main(final String[] args) {
Animal[] animals = new Animal[10];
Animal p0 = new Liger();
p0.size = 11;
animals[0] = p0;
Animal p1 = new Liger();
animals[1] = p1;
System.out.println("p0.size "+ p0.size); // call as a superclass instance
System.out.println("real p0.size "+ ((p0 instanceof Liger) ? ((Liger)p0).size : ((Tiger)p0).size) ); // cast to call the effective instance of the subclass
System.out.println("p1.size "+ p1.size); // call as a superclass instance
System.out.println("real p1.size "+ ((p1 instanceof Liger) ? ((Liger)p1).size : ((Tiger)p1).size) ); // cast to call the effective instance of the subclass
}
public abstract class Animal {
private int size;
public Animal() {
size = -1;
}
public Animal(int size) {
this.size = size;
}
public void setSize( int size ) {
this.size = size;
}
public int getSize() {
return size;
}
public static void main(final String[] args) {
Animal[] animals = new Animal[2];
animals[0] = new Liger(20);
animals[1] = new Liger();
for(int i = 0; i < animals.length; ++i) {
System.out.println("Size : " + animals[i].getSize());
}
}
}
public class Tiger extends Animal {
public Tiger() {
super();
}
public Tiger(int size) {
super(size);
}
}
public class Liger extends Animal {
public Liger() {
super();
}
public Liger(int size) {
super(size);
}
}
This is just a basic guideline, just for reference. The point here is behaviour can be overridden in subsequent child classes. Java Tutorial
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.