Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How do you access a parent class method two levels down?

I have a class that extends a class that I need to overide, but I need to call that class's parent class. since I can't call super since that will execute the direct parent what is the best way to get the parent of my parent class?

I am sure this is a basic question, but its been a while since I have been doing any java.

class A {  public void myMethod()  { /* ... */ } }  class B extends A {  public void myMethod()  { /* Another code */ } }  class C extends B {  I need to call Class A here  { /* Another code */ } } 
like image 385
dan.codes Avatar asked Jun 25 '10 12:06

dan.codes


People also ask

How do you access parent class methods?

Using Classname: Parent's class methods can be called by using the Parent classname. method inside the overridden method. Using Super(): Python super() function provides us the facility to refer to the parent class explicitly.

How do I access the superclass method?

3. Use of super() to access superclass constructor. As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() .

How do you call an inherited method in Java?

you need to override the method getName(). it's instance level function you can call it in child class but you cannot modify it without overriding the function. So it's calling parent class function with parent class property. just override the method if you want "cat" in output.


2 Answers

You don't: it violates encapsulation.

It's fine to say, "No, I don't want my own behaviour - I want my parent's behaviour" because it's assumed that you'll only do so when it maintains your own state correctly.

However, you can't bypass your parent's behaviour - that would stop it from enforcing its own consistency. If the parent class wants to allow you to call the grandparent method directly, it can expose that via a separate method... but that's up to the parent class.

like image 178
Jon Skeet Avatar answered Sep 22 '22 17:09

Jon Skeet


You can't because it has been overridden by B. There is no instance of A inside C.

The thing is that you want to call a method of the class A, but from which instance? You have instantiated C, which is a class with a couple of own and inherited methods from B. If B is overriding a method of A, you can't access it from C, because the method itself belongs to C (is not a method of B, it has been inherited and now it's in C)

Possible workarounds:

B does not override myMethod()

C receives an instance of A and saves it as a class property.

myMethod() in A is static and you use A.myMethod() (I don't recommend it)

like image 40
pakore Avatar answered Sep 19 '22 17:09

pakore