Can you have a class which implements an interface, and choose whether to use the methods in the interface during instantiation of this class? Therefore having object A which uses the interface and object B which does not use it.
Thanks
Updated:
Assuming you have a Professor class and this class implements an interface called Employer, which has employ(rAssist x) abstract method.
Now I want to instantiated 2 objects from the Professor class implementing this interface Object A – Professor can employ a research assistant and Object B – Professor cannot employ research assistants.
No, if class
Cimplements the interface, then all instances ofCwill provide the methods declared in the interface.What you can do is something like
and then do
In effect,
xsupports the use ofinterfaceMethodwhileydoes not. Note however that…The usage of
y.interfaceMethodis not prevented at compile-time, i.e. it will not be enforced by the type system.With this solution, you are in fact creating an (anonymous) subclass of
MyClassand assigning an instance of it toy.