简体   繁体   中英

to use same method of superclass for object of subclass

class A {
    void test() {
    }
}

class B extends A {
    void test() {
    }

 public static void main(String[] args)
{
 B b=new B();
//insert code here
}
}

How can I call the test method of class A for object b of class B ? specifically for object b

You can't call it from outside B... but within B you can call it as:

super.test();

This can be done from any code within B - it doesn't have to be in the test() method itself. So for example:

public void foo() {
    // Call the superclass implementation directly - no logging
    super.test();
}

@Override void test() {
    System.out.println("About to call super.test()");
    super.test();
    System.out.println("Call to super.test() complete");
}

Note the @Override annotation which tells the compiler that you really did mean to override a method. (Aside from anything else, if you have a typo in the method name, this will help you find it quickly.)

The reason you can't call it from outside B is that B overrides the method... the purpose of overriding is to replace the original behaviour. For example, in a method with a parameter, B may wish to do something with the parameter (validate it according to its own rules) before either calling the superclass implementation or doing something else. If outside code could just call A's version, that would violate B's expectations (and encapsulation).

The class itself is error. You should not add the parenthesis while defining class names. You can use either object type casting or call super.test() in the test method of class B

class A
 {
 test()
 {}
 }

   class B extends A
  {
  test()
  {
   super.test()   // calls the test() method of base class
   }
   }


  B b=new B();

这可用于使用派生类对象调用基类方法。

b.super.test()

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