Init parent class with a Child contstructor in Java, theory -


i've tested code.

main.

public class main {      /**      * @param args      */     public static void main(string[] args) {         parent parent = new child(12, "lorem", 12);         if (parent instanceof parent) {             system.out.println("parent");         } else if (parent instanceof child) {             system.out.println("child");         }         outchild(parent);     }      private static void outchild(parent parent) {         child child = (child) parent;         system.out.print(child);     } } 

parent.

public class parent {      int id;     string name;      public parent(int id, string name) {         this.id = id;         this.name = name;     }  } 

child.

public class child extends parent {      int extra;      public child(int id, string name, int extra) {         super(id, name);         this.extra = extra;     }      @override     public string tostring() {         return "id: " + id + ", name: " + name + ", extra: " + extra;     }  } 

i need theory. why parent instance considered parent class instance has extra field declared in child only?

if had written parent parent = new parent(12, "lorem"); , called outchild(parent parent), have gotten classcastexception.

your parent parent reference, not object. means have reference parent minimum, sub class.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -