Java inheritance and methods

  public class TestBoss {

      public static void main(String[] args) {
                  Worker duck = new Worker();

                  (Boss) duck.type();
       }

 public class Boss{
       //stuff
 }

 public class Worker extends Boss{
       public void type(){
        //stuff
       }
 }

      

If there was a superclass called boss and a subclass called worker. So if there was a testing class that had to use the method in the working class. The duck object in this case is of type Boss / In, but the method of the type is only used in the working class, not in the boss class. however java requires the Boss class to contain a type method, although it was not used. How do I make a method declared only in the working class, or should the boss class have a filler method that essentially does nothing?

+3


source to share


4 answers


Use the interface. Make an Worker

implementation of this interface, but don't Boss

.



 public class Worker extends Boss implements YourInterface
 {
  ...
 }

 interface YourInterface
 {
       public void type();
 }

      

+1


source


If only Worker

provides a method type()

, you need to cast the object back to Worker

before you can use it. For example.



Worker duck = new Worker();
...
Boss boss = (Boss)duck;
...
if (boss instanceof Worker) // check in case you don't know 100% if boss is actually a worker
{
    (Worker)boss.type();
}

      

+4


source


This is the basic principle OOP

.. You can only call a method with a parent reference that exists in the parent ..

Boss boss=new Worker();

      

using the boss

u method only for the call that exists in Boss coz when checking for the existence of the finalizer in the parent class in the above case.

So, you only have 2 ways to call the child class's private method.
1st: - create the same method in your parent. The parent can be interface or class

as deporter .
2nd: - Or downcast

to your child class.

(Worker)boss.type();

      

+1


source


Try it....

 public class TestBoss {

          public static void main(String[] args) {
Boss duck = new Worker();
                      ((Worker) duck).type();
           }

     public class Boss{
           //stuff
     }

     public class Worker extends Boss{
           public void type(){
            //stuff
           }
     }

      

0


source







All Articles