在抽象类java中调用非抽象方法 [英] calling non abstract method in abstract class java

查看:1362
本文介绍了在抽象类java中调用非抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3节课。这似乎是基本问题。但我不能通过谷歌搜索找到答案。

I have 3 classes. It seems basic question. But I can'nt find answer by googling.

public abstract class Test {

    void t1()
    {
        System.out.println("super");

    }

}
 public class concret extends Test{

    void t1()
    {
        System.out.println("child");

    }
    void t2()
    {
        System.out.println("child2");

    }

}

public class run {
    public static void main(String[] args) {
        Test t=new concret();

        t.t1();
    }

}

如何调用抽象类t1方法?由于我无法从抽象类创建对象,如何在抽象类中调用t1?
谢谢。

How do I call abstract class t1 method? Since I cant create object from abstract class how do I call t1 in abstract class? Thank you.

推荐答案

要么创建一个覆盖的具体类方法,或在 覆盖方法的具体类中,您可以调用 super.t1()。例如:

Either you create a concrete class which doesn't override the method, or within a concrete class which does override the method, you can call super.t1(). For example:

void t1()
{
    super.t1(); // First call the superclass implementation
    System.out.println("child");
}

如果您只有一个覆盖方法的对象实例,你不能从类的外部调用原始方法,因为这会破坏封装...覆盖的目的是替换原始方法的行为。

If you've only got an instance of an object which overrides a method, you cannot call the original method from "outside" the class, because that would break encapsulation... the purpose of overriding is to replace the behaviour of the original method.

这篇关于在抽象类java中调用非抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆