Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and Methods in Java

  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 test class that needed to use a method in the worker class. The object duck in this case is type casted into Boss/ In the code though, the type method is only usable in the worker class and not in the boss class. however java requires that Boss class contains the type method even though it's not used. How does one make the method declared only in the worker class or does boss class need to have a filler method that essentially does nothing?

like image 231
Index Hacker Avatar asked Jan 19 '26 07:01

Index Hacker


2 Answers

If only Worker exposes the method type() then you need to cast your object back to Worker before you can use it. E.g.

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();
}
like image 52
ChrisWue Avatar answered Jan 21 '26 22:01

ChrisWue


Use an interface. Make Worker implementing that interface, but not Boss.

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

 interface YourInterface
 {
       public void type();
 }
like image 27
Juvanis Avatar answered Jan 21 '26 22:01

Juvanis