简体   繁体   中英

Understanding the Java Base class and Derived Class

I was searching the internet to understand the concept of Base class and derived class. I have a question on if derived class contains all the variables and methods of a base class or derived class just refers to base class variables and methods.

When I extend a class from Base class and create an object of derived class, does the derived class object act as container containing a Base class object + its own variables and methods? Is the Base class object copied inline? When I call super class method super.setValues(10,20), does it call Super class, set the values and copy these value inline?

I am confused over the internal workings of the code? Can somebody please explain?

Thanks Gauri

As I understand it, going to the lowest level, when you instantiate a derived class in a statically typed language, it is stored in memory with the parent class delimited in memory from the child class. When you access the instance, based on what type you retrieve it as, it will access the same memory area as either the entire memory area of the instance or only the base part area of the memory. However the base class methods will point towards the derived class in case they're overridden in derived classes.

It's not a good answer, it's just how it's been retained in my memory while working in OOP environments.

In any case there are tons of literature on the subject which can help you clarify OOP better than I ever could in a SO answer.

When you are extending a class, the derived class actually inherits methods from base class.The derived class object contains all the methods and variables of derived class and super class.But if any methods are overridden, the derived class object refers to overridden method. That means first priority goes to derived class.If compiler does not find that method in derived class, then it checks in base class.

super.setValues(10,20) calls super class method since you have used super keyword.If you use it without super keyword, then it checks in derived class first.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM