有没有办法禁止子类在java中调用超类的公共方法? [英] Is there any way to forbid the son class to call the public method of super class in java?

查看:122
本文介绍了有没有办法禁止子类在java中调用超类的公共方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法禁止子类在java中调用超类的公共方法?

Is there any way to forbid the son class to call the public method of super class in java?

例如

public abstract class TObject{
    abstract public void quark();
}


public class Animal extends TObject{

       public void quark(){
           System.out.println("this is the animal");
       }

}

public class Dog extends Animal{
       @overide
       public void quark(){
           System.out.println("this is the animal");
           **super.quark();**
       }
} 

In this example, The Dog call the **super.quark();** in it's quark method.

但我不希望Dog可以调用 super.quark(); 我也不想将Animal中夸克方法的

But I don't want the Dog could call super.quark(); and I also don't want to change the

修饰符更改为私有。有没有办法在编译时阻止这种情况?

modifier of quark method in Animal to private. Is there any way to prevent this in compile?

我已经困惑了几天,谁能帮助我........

I have be confused couple of days, who can help me........

我这样做的原因是我在开发 hudson scm插件时遇到了类似的问题。我

The reason I do that is I met the similar problem in developing hudson scm plugin.I

创建了扩展SubversionSCM(官方类)的类。我只想

created the class which extends the SubversionSCM(the offical class). I just wanted to

覆盖超类的公共方法,然后调用super的公共方法,如

override the public method of super class, then call super's public method back like

示例。但编译给出了错误。我不知道为什么,怎么办?剂量java

example. but the compile gave error.I don't konw why, how could it do? Dose java have

类似反映方式以防止这种情况?

推荐答案

不,根据 public 的定义,您无法停止调用该方法(无论是派生类还是其他任何位置)。您当然可以阻止它被覆盖(从而确保用于调用它的语法不会使用 super ;-)它最终

No, by definition of public you can't stop the method from being called (whether from a derived class or anywhere else). You can of course stop it from being overridden (and thereby ensure that the syntax used to call it won't use super;-) by making it final.

这篇关于有没有办法禁止子类在java中调用超类的公共方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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