1

please note to this. I have a super class

class A
{
    public void update(int num)
    {...}
}

and have a other class. inherit of class A

class B extends A
{
   public void update(string str)
   {...}
}

B obj = new B();
obj.update(50); // oh no, bad
obj.update(""); // yes

now, i want that when i create new from class B the update() of class A not access. -in other words i want access to the update() method of B only

Ali Bagheri
  • 3,068
  • 27
  • 28
  • 3
    http://stackoverflow.com/questions/5486402/disabling-inherited-method-on-derived-class – Harsha W Mar 27 '17 at 05:56
  • What you've done is like Overloading the `update` method because it has the same name but different parameters. So, in your case, Use String so you can prevent the update of the Super Class. – msagala25 Mar 27 '17 at 06:17
  • 1
    if it is the case, then from design perspective B is not a subclass of A. so your whole design is incorrect, if someone came across with this kind of requirement, first review the design. – hunter Mar 27 '17 at 06:39

3 Answers3

0

You can prevent that only when you have the same method name with same arguments in super type and sub type effectively overriding it. In your case, the method the signatues are different.. they take different arguments, hence based on what you pass as argument, it calls the respective method.

OTM
  • 656
  • 5
  • 8
0

Actually you can override that method and throw an exception is a solution.

class A
{
    public void update(int num)
    {...}
}

class B extends A
{
   public void update(int i) { 
       throw new UnsupprotedOperationException();
   }
   public void update(string str)
   {...}
}

Or you can implement a class with generics. This may be not working but idea works.

class A<T>
{
    public void update(T num)
    {...}
}

class B extends A<String>
{
   public void update(String str)
   {...}
}
utkusonmez
  • 1,486
  • 15
  • 22
0

Make your base class method private.

class A
{
    private void update(int num)
    {

    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65