简体   繁体   English

对子类的对象使用相同的超类方法

[英]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 ? 如何为类B的对象b调用类A的test方法? specifically for object b 专门针对对象b

You can't call it from outside B... but within B you can call it as: 您不能从B 外部调用它,但是 B 可以将其称为:

super.test();

This can be done from any code within B - it doesn't have to be in the test() method itself. 可以从B内的任何代码完成此操作-不必在test()方法本身中。 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. 请注意@Override批注,该批注告诉编译器您确实确实打算重写方法。 (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. 您不能从外部B调用它的原因是B 覆盖了该方法... 覆盖的目的是替换原始行为。 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. 例如,在具有参数的方法中,B可能希望在调用超类实现或执行其他操作之前,对该参数执行某些操作(根据其自身的规则对其进行验证)。 If outside code could just call A's version, that would violate B's expectations (and encapsulation). 如果外部代码只能调用A的版本,那将违反B的期望(和封装)。

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 您可以使用对象类型转换或在B类的test方法中调用super.test()

class A
 {
 test()
 {}
 }

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


  B b=new B();

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

b.super.test()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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