Override (1)

See a sample:
———-TestOverride.java———–
package ch.allenstudy.newway02;

public class TestOverride {
public static void main(String[] zhangsan)
{
B bb = new B();
bb.f();
}
}
class A
{
public void f()
{
System.out.printf(“AAAA\n”);
}
}
class B extends A
{
public void f() //this is OVERRIDE the method f();
{
System.out.printf(“BBBB\n”);
}
}
———Result———
BBBB

Whether we also can call the f() method of the superclass in B’s f() method?
Yes, we can.
Just add one line as below:
———-TestOverride.java———–
package ch.allenstudy.newway02;

public class TestOverride {
public static void main(String[] zhangsan)
{
B bb = new B();
bb.f();
}
}
class A
{
public void f()
{
System.out.printf(“AAAA\n”);
}
}
class B extends A
{
public void f() //this is OVERRIDE the method f();
{
super.f(); //super 就是指父类。所以这里就调用了父类的 f() 方法。
System.out.printf(“BBBB\n”);
}
}
———Result———
AAAA
BBBB

虽然我们这里实现了在override 方法的时候调用superclass的方法,但是很少有这么用的。

原文地址:https://www.cnblogs.com/backpacker/p/2271566.html