简体   繁体   中英

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

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

For example

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.

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........

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

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

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

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

something like reflect way s to prevent this?

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 .

No, there's no way to have a public method that subclasses can't call. The best you can do is document this recommendation.

As a note, it's called a subclass or child class.

The other 2 answers ( Alex & Matthew) are basically right.

  1. you can prevent the subclass from calling a public method from the super class
  2. there is probably something wrong with your design if you do this.

The below Father class has two public methods named fatherMethod. Subclasses can call the fatherMethod using reflection (Thank You Matthew for pointing that out.) Without using reflection, subclasses can probably not call either fatherMethod method. Thus it is very similar to a private method.

class Father
{
    private class Alpha { }

    private class Beta { }

    public void fatherMethod ( Alpha param )
    {
    }

    public void fatherMethod ( Beta param )
    {
    }
}

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