Index Hacker
Index Hacker

Reputation: 2024

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?

Upvotes: 3

Views: 159

Answers (4)

user1237385
user1237385

Reputation:

Try this....

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

Upvotes: 0

ChrisWue
ChrisWue

Reputation: 19020

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();
}

Upvotes: 4

Sumit Singh
Sumit Singh

Reputation: 15886

This is basic principal of OOP.. You can call Only those method with parents reference , which is exist in Parent..

Boss boss=new Worker();

using boss u call only method which is exist in Boss coz at time of completion method existence check in parent class in above case..

So You have only 2 way to call a personal method of child class..
1st :- create same method in your parent. Parent may be interface or class like deporter said.
2nd :- Or downcast it into your child class..

(Worker)boss.type();

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

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

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

 interface YourInterface
 {
       public void type();
 }

Upvotes: 1

Related Questions