Understanding the concept of inheritance in Java -


I just refresh Java's Oops features. Therefore, I have some confusion about the concept of heritage, for that I have A sample code is:

  class super {int index = 5; Public zero printVal () {System.out.println ("super"); }} Expanded {int index = 2; Public Zero printVal () {System.out.println ("sub"); }} Public square runner {public static zero main (string argument []) {super super = new sub (); Println (sup.index + ","); Sup.printVal ();  

Now the above code gives me the output: 5, sub.

Here, we are overriding the print-up method (), so it is understood that it is only using the child class system.

But I did not understand why it was reaching the value of X from the super class ...

Thank you in advance .. ..

< / Div>

There are types of objects, and variables are the type because you have:

  super Super = new sub ();  

You now have a sup type super , which refers to the object of type is.

When you call a method on an object, the method that is run is chosen based on the type of object , which is why it is called "super Instead of "all" prints.

When you access a field in the object, the field is selected based on the type of variable , that is why you get 5.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -