java - Polymorphism on simple example -
i think i'm starting understand topic, not completely. can explain me on example:
public class solution { public static void main(string[] args) { cow cow = new whale(); system.out.println(cow.getname()); } public static class cow { public string getname() { return "im cow"; } } public static class whale extends cow { public string getname() { return "im whale"; } } }
what difference when called this:
cow cow = new whale(); system.out.println(cow.getname());
and this:
whale whale = new whale();
system.out.println(whale.getname());
i have same output, in cases or maybe when should call methods cow class, , when form whale class. sorry if gave stupid or simple example. hope undeerstood wanted say. in advance.
it's question understand polymorphism. not sure whale should extends cow ;), can show bit of different structure:
public class solution { public static void main(string[] args) { animal animal1 = new cow(); animal animal2 = new whale(); arraylist<animal> myanimals = new arraylist<animal>(); myanimals.add(animal1); myanimals.add(animal2); //show animals (animal animal : arraylist) { system.out.println(animal.getname()); } } public static class animal { public string getname() { return "im general animal"; } } public static class cow extends animal { public string getname() { return "im cow"; } } public static class whale extends animal { public string getname() { return "im whale"; } } }
in above example created animal class extended cow , whale. can create list of animals , display names. in example no difference make object cow cow = new whale(); , whale whale = new whale(); clear you?
Comments
Post a Comment