简体   繁体   中英

How can you invoke a method from a grand parent class?

There was a question in the exam that says

If class A extends Class B and B extends Class C. And they all have the method test()

How to invoke the method test that in class C in class A ?

I stupidly chose. Super.super.test(). Which I think it's wrong.

Th other options were:

Test() Super.test(). I thought about this. But if I used this it will invoke the method in class B and class B will invoke the method in Class C But we only want C

Sorry if this is not very clear or not organized just finish exam and kinda dizzy.

There is no way you access the method of super - super class. If the class B override the automatically when you run the super will run both the instructions contained in the class B, as in class C. Now if you ensure that there is no instruction implemented in class B, you will automatically execute only the instructions of the class C.

If the class B has instructions that you did not want to run, duplicate the method by changing the name and run from the class A using the identifier super.

It is not possible to do so. Only through invoking the superclass method, which in turn invokes the method in its superclass (C)

This is possible in C++ but not in Java. super always redirects you to immediate parent.

The super.super() is not allowed in java. Try it this way if you really want , you can implement that by yourself :

public class abc {  
        public void myName(){  
            System.out.println("abc");  
        }  
    }  

    public class def extends abc {  
        public void myName(boolean flag){  
            if(flag){   
                super.myName();  
            }else {  
                System.out.println("def");  
            }  
        }  
    }  



    public class mno {
        public static void main(String[] args){
            def d = new def();

            System.out.print("This returns the so called 'super.super' : ");
            d.myName(true);

        }
    }

output : This returns the so called 'super.super' : abc

I would imagine the below would print out "A". I do not have a compiler convenient to try it out.

class A
{
     private void test ( ) { System . out . println ( "A" ) ; }

     public static void main ( String [ ] args )
     {
          C c = new C ( ) ;
          c . test ( ) ;
     }
}


class B extends A
{
     private void test ( ) { System . out . println ( "A" ) ; }
}


class C extends B
{
     private void test ( ) { System . out . println ( "A" ) ; }
}

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