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?
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();
}
Use an interface. Make Worker implementing that interface, but not Boss.
public class Worker extends Boss implements YourInterface
{
...
}
interface YourInterface
{
public void type();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With