In: Computer Science
public class Mammal extends SeaCreature {
public void method1() {
System.out.println("warm-blooded");
}
}
public class SeaCreature {
public void method1() {
System.out.println("creature 1");
}
public void method2() {
System.out.println("creature 2");
}
public String toString() {
return "ocean-dwelling";
}
}
public class Whale extends Mammal {
public void method1() {
System.out.println("spout");
}
public String toString() {
return "BIG!";
}
}
public class Squid extends SeaCreature {
public void method2() {
System.out.println("tentacles");
}
public String toString() {
return "squid";
}
}
// Driver code
public class ByTheSea {
public static void main(String[] args) {
SeaCreature[] elements = {new Squid(), new Whale(), new SeaCreature(),
new Mammal()};
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
elements[i].method1();
elements[i].method2();
System.out.println();
}
}
}
the output of the above program is:
This is because in a java code there can be only one Public Class. But in the above code, all the classes provided are public.
For this program to work, you have to create separate java files for these class.
Or you can remove the public keyword from all other classes.
You also have to reorder the classes because some classes are inheriting from others.
class SeaCreature {
public void method1() {
System.out.println("creature 1");
}
public void method2() {
System.out.println("creature 2");
}
public String toString() {
return "ocean-dwelling";
}
}
class Mammal extends SeaCreature {
public void method1() {
System.out.println("warm-blooded");
}
}
class Squid extends SeaCreature {
public void method2() {
System.out.println("tentacles");
}
public String toString() {
return "squid";
}
}
class Whale extends Mammal {
public void method1() {
System.out.println("spout");
}
public String toString() {
return "BIG!";
}
}
public class ByTheSea {
public static void main(String[] args) {
SeaCreature[] elements = {new Squid(), new Whale(), new SeaCreature(), new Mammal()};
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
elements[i].method1();
elements[i].method2();
System.out.println();
}
}
}
The output will be:
I hope this answers your question.
thanks for asking