3
  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?

4 Answers 4

4

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain what does Boss boss = (Boss)worker; mean here? Without creating a worker instance you can cast it eh? Please elucidate.
Oh sorry, that was supposed to be Boss boss = (Boss)duck;
Aah, it was a typo. Lol, I thought it was something which I didn't know and could learn :P
1

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

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

 interface YourInterface
 {
       public void type();
 }

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.