how to avoid using a empty method implementation? - java

I have a question regarding the structures of my classes in java :
I have a first class : MyClass that is abstract
public abstract class MyClass
{
protected void abstract monitor();
}
then I have an abstract iterator on it
public abstract class MyClassIterator<T> extends MyClass
{
protected void abstract monitor(T data);
}
In practice I will after create classes that will either inherit from MyClass or MyClassIterator.
I want to make sure all instances of MyClass implement monitor but for the iterator ones, how can I avoid inserting something like
protected void monitor() {};
just to implement it :/
Thanks for any idea :)

Add a default implementation of monitor in MyClass, with a customized exception
public abstract class MyClass
{
protected void abstract monitor()
{
throw new NotImplementedException();
}
}
Thereby, MyClassIterator won't have to implement the method and other subclasses of MyClass will have to override it.

If you don't want that MyClassIterator subclasses will have to implement this method, then you have to add the empty implementation to MyClassIterator.
You can also throw some exception in the implementation.
public abstract class MyClassIterator<T> extends MyClass
{
protected abstract void monitor(T data);
protected void monitor() {
//optional
throw new UnsupportedOperationException();
}
}
Note: You can't write void before abstract, you need to fix this in your monitor(T data) method, like in my answer.

Related

How could I call an abstract class method who is common between subclasses without instanciating any subclass

I have a code like this :
interface Contract {
createSomething(); //not common
updateSomething(); //not common
getSomething(); //method who is supposed to be common between all strategies
}
interface Strategy {
createSomething();
updateSomething();
getSomething();
}
Abstract class AbstractStrategy implements Strategy {
#Override
getSomething() {
// the common code
}
}
class strategyA extends AbstractStrategy {
#Override
createSomething() {...}
#Override
updateSomething() {...}
}
class ContractImpl implements Contract {
#Override
createSomething() {
//get the good strategy
//call the strategy.createSomething();
}
#Override
updateSomething() {
//get the good strategy
//call the strategy.updateSomething();
}
#Override
getSomething() {
**Here is the question**
}
}
Question:
How could I rewrite this code so I could call the getSomething() method without having to instanciate a random subclass just to call it with the super keyword ?
You can't. Rather, you could extract the code into a static method and subsequently call it from getSomething(). This would allow you to call it statically when you need to, and from an instance when needed as well.
In other words, your AbstractStrategy class should look like:
Abstract class AbstractStrategy implements Strategy {
public static void sharedCode(parameters needed) {
// the common code
}
#Override
(signature) getSomething() {
sharedCode(this.parametersNeeded);
}
}
You basically can't. An abstract class can't be instantiated, so you can't call an instance method without having an object of a concrete implementation (in your case any concrete subclass of AbstractStrategy).
One option that you have is to create an anonymous class so that you can call the method without instantiating any of your subclasses of AbstractStrategy:
AbstractStrategy strategy = new AbstractStrategy() {
#Override
createSomething() {...}
#Override
updateSomething() {...}
}
strategy.getSomething();
But this feels hacky.

Is there a way in Java to call different child method depending on which subclass is the object?

In my project I have a superclass and two subclasses extending from it. There is a method in the superclass that is overriden differently in each subclass.
I want to know if it's possible to introduce a method (in another class) that takes object of either subclass as a parameter and calls a method overriden in one of subclasses (depending on to which subclass does the object belong).
public class Superclass{
public int method(){return 0;}
}
public class Subclass1 extends Superclass{
public int method(){return 1;}
}
public class Subclass2 extends Superclass{
public int method(){return 2;}
}
public class CallingClass{
public static int dependantCall(Superclass parameter){return parameter.method}
I want to be able to do something like
Subclass1 subclassObject = new Subclass1;
System.out.println(CallingClass.dependantCall(subclassObject));
and get output
1
That is what Polymorphism is for! Defining the Superclass as a parameter type will allow you to pass either subclass in.
For example in your other class you can define it like this:
// classes Dog and Cat extend Animal and override makeNoise()
class Owner{
playWith(Animal a){
a.makeNoise();
}
}
Now the Owner can accept owner.makeNoise(cat) and owner.makeNoise(dog)
More reading: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
Yes, it is entirely possible. Here's how that method would look like:
public <T extends Superclass> void foo(T subclassObject) {
...
}
Or:
public void foo(Superclass obj) {
...
}
Note that in the above method, you can pass subclasses' objects as well (they are covariant data types).
This is what Java does by default when you create subclases, so no need to do anything special. Each object carries it's type information at run time, and the method invoked would always be the most specific one for the object. Example:
public class Doer {
public void doSomething() {
// Body presence
};
}
public class Painter extends Doer {
#Override
public void doSomething() {
// Paint here
}
}
public class Manager extends Doer {
#Override
public void doSomething() {
// Micromanage here
}
}
// Elsewhere in your code:
public void busyness(Doer doer) {
doer.doSomething();
}
A style note: if it is possible, one should prefer using interfaces instead of base classes (base classes those should be used only if you want to share implementation between subclasses). Example with interfaces:
public interface Doer {
void doSomething();
}
public class JackOfAllTrades implements Does {
#Override
public void doSomething() {
// Do whatever necessary
}
}
// Client code stays exactly the same as above:
public void busyness(Doer doer) {
doer.doSomething();
}
Note that in Java a class can have only one base class but can implement multiple interfaces.
#Override annotations are not strictly required, but they help Java compiler to spot some errors for you (e.g. if you misprint method name).
In your example it would look like
public class CallingClass {
public static int dependantCall(Superclass parameter) {
return parameter.method();
}
}
Subclass1 subclassObject = new Subclass1();
System.out.println(CallingClass.dependantCall(subclassObject));

How to protect a method implementing an interface from overriding?

I have interface:
public interface Doable {
void doSomething();
}
and the class that implements it:
public class DoJump() implements Doable {
#Override
private void doSomething() {
fireJumpHandler();
}
}
This is stupid example, but I would like to present the problem.
This code doesn't compile, I am getting an error in Eclipse IDE:
Cannot reduce the visibility of the inherited method from
Doable
I have common interface that declares a method. This method is overriden in concrete class. I would like to avoid another class that can extend this class (DoJump), so I would like to hide this method from sub classes. I would like to use private modifier, but Java does not allow me to do it.
Why it is impossible, and how to workaround it?
I'd like to answer your last question "How to workaround it?" as this is not described in the related question. Create a second interface NotDoable which simply does not have doSomething() declared. Then let your DoJump implement both interfaces. Give everyone that shouldn't override doSomething a reference to the interface NotDoable instead of the true type DoJump. Then they won't know that the object truly can doSomething, they won't know per class design. Of course, one can workaround this but one actually can workaround everything. The class design is more correct this way. Here's some code:
public interface Doable {
public void doSomething();
}
public interface NotDoable {
}
public class DoJump implements Doable, NotDoable {
#Override
public void doSomething() {
System.out.println("hi");
}
public NotDoable meAsNotDoable() {
return this;
}
public static void main(String[] args) {
DoJump object = new DoJump();
// This call is possible, no errors
object.doSomething();
NotDoable hidden = object.meAsNotDoable();
// Not possible, compile error, the true type is hidden!
hidden.doSomething();
}
}
But as said, one can workaround this by using if (hidden instanceof DoJump) { DoJump trueObject = (DoJump) hidden; }. But well, one can also access private values via reflection.
Other classes now implement NotDoable instead of extending DoJump. If you declare everything others should know about DoJump in this interface, then they only can do what they should do. You may call this interface IDoJump and the implementing class DoJump, a common pattern.
Now the same a bit more concrete.
public interface IDog {
public void bark();
}
public interface ICanFly {
public void fly();
}
public class FlyingDog implements IDog, ICanFly {
#Override
public void bark() {
System.out.println("wuff");
}
#Override
public void fly() {
System.out.println("Whuiiii");
}
public static void main(String[] args) {
FlyingDog flyingDog = new FlyingDog();
// Both works
flyingDog.fly();
flyingDog.bark();
IDog dog = (IDog) flyingDog;
// Same object but does not work, compile error
dog.fly();
ICanFly canFly = (ICanFly) flyingDog;
// Same object but does not work, compile error
canFly.bark();
}
}
And now an extending class.
public class LoudDog implements IDog {
#Override
public void bark() {
System.out.println("WUUUUFF");
}
// Does not work, compile error as IDog does not declare this method
#Override
public void fly() {
System.out.println("I wanna fly :(");
}
}
In the end, be aware that if others know that their IDog actually is a FlyingDog (and they cast it), then they must be able to call fly() as a FlyingDog must can fly. Furthermore, they must be able to override the behavior as long as they follow the specification of fly() given by its method-signature. Imagine a subclass called PoorFlyingDog, he needs to override the default behavior, else he can perfectly fly, but he is a poor flyer.
Summarized: Hide to others that you're actually a DoJump, also hide that you are a Doable, pretend to only be a NotDoable. Or with the animals, pretend to only be an IDog instead of a FlyingDog or ICanFly. If the others don't cheat (casting), they won't be able to use fly() on you, though you actually can fly.
Add final to DoJump declaration to prevent this class to be overriden (and therefore doSomething() to be overriden too).
public final class DoJump implements Doable {
#Override
public void doSomething() {
fireJumpHandler();
}
}
If you still need to be able to inherit DoJump but you don't want doSomething() to be overriden, put the final modifier in the method signature
public class DoJump implements Doable {
#Override
public final void doSomething() {
fireJumpHandler();
}
}

Extending an abstract class - implementing abstract methods

Greetings and salutations!
I currently have an abstract class A, and many classes subclassing it. The code is common to all the subclasses I've put in the oneMethod() and the code that's specific to each implementation I've put into two abstract methods.
public abstract class AbstractA {
public oneMethod() {
//do some intelligent stuff here
abstractMethodOne();
abstractMethodTwo();
}
protected abstract void abstractMethodOne();
protected abstract void abstractMethodTwo();
}
I have a class that overrides the oneMethod() method.
public class B extends AbstractA {
#Override
public oneMethod() {
//do some other intelligent stuff here
}
}
Is there any way to skip making a stub implementation of the two abstract methods in the subclass? I mean the only place they're used is in the overridden method.
Any help is appreciated!
No. If you extend an abstract class, you must either make the child class abstract or it must fulfill the contract of the parent class.
As a design observation, I would suggest that you try to make oneMethod() either final or abstract. It's hard to maintain programs that allow extension the way you're implementing it. Use other abstract methods to give child classes hooks into the functionality of oneMethod().
You have to provide an implementation to all abstract methods. Even if no part of the program calls them now a class can be created in the future that does call them, or the super class implementation may be changed. A stub is needed even if it's just for binary compatibility.
Just make class B also abstract.
public abstract class B extends AbstractA {
You could pull oneMethod up into a superclass:
public abstract class AbstractC {
public void oneMethod() {
}
}
public abstract class AbstractA extends AbstractC {
#Override
public void oneMethod() {
//do some intelligent stuff here
abstractMethodOne();
abstractMethodTwo();
}
protected abstract void abstractMethodOne();
protected abstract void abstractMethodTwo();
}
public class B extends AbstractC {
#Override
public void oneMethod() {
//do some other intelligent stuff here
}
}
see now how you don't need any more in AbstractC than you need.
Since abstractMethodOne() and abstractMethodTwo() are implementation specific but you know that you will always call them you can use composition like this:
public interface SomeInterface {
void abstractMethodOne();
void abstractMethodTwo();
}
and create a class like this:
public class SomeClass {
public void executeThem(SomeInterface onSomeObject) {
onSomeObject.abstractMethodOne();
onSomeObject.abstractMethodTwo();
}
}
then you can compose this in any of your classes where you should call those methods like this:
public class SomeImplementation implements SomeInterface {
public void abstractMethodOne() {
// ...
}
public void abstractMethodTwo() {
// ...
}
public void executeThem() {
new SomeClass().executeThem(this);
}
}
This way you got rid of the inheritance altogether and you can be more flexible in your classes implementing SomeInterface.
If your classes B and A have to implement their own oneMethod it's maybe because there are not in an inheritance link but they just should implement the same interface ?
Well, if abstractMethodTwo and abstractMethodOne are implementation specific, why you put these methods in the base abstract class ? Maybe a common interface or some specific design-pattern is what you're looking for!
An abstract method from an abstract class can be used in a class in the way shown below. I would appreciate your opinion if you find any wrong in my answer. Thank you.
Code using Java
public abstract class AbstractClassA {
protected abstract void method1();
public abstract void method2();
}
public class ClassB extends AbstractClassA{
#Override
protected void method1(){}
public void method2(){}
}

Extending functionality of all implementations of an Interface?

I'm looking to create a set of functions which all implementations of a certain Interface can be extended to use. My question is whether there's a way to do this without using a proxy or manually extending each implementation of the interface?
My initial idea was to see if it was possible to use generics; using a parameterized type as the super type of my implementation...
public class NewFunctionality<T extends OldFunctionality> extends T {
//...
}
...but this is illegal. I don't exactly know why this is illegal, but it does sort of feel right that it is (probably because T could itself be an interface rather than an implementation).
Are there any other ways to achieve what I'm trying to do?
EDIT One example of something I might want to do is to extend java.util.List... Using my dodgy, illegal syntax:
public class FilterByType<T extends List> extends T {
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
}
You can achieve something like this using a programming pattern known as a 'decorator' (although if the interface is large then unfortunately this is a bit verbose to implement in Java because you need to write single-line implementations of every method in the interface):
public class FilterByType<T> implements List<T> {
private List<T> _list;
public FilterByType(List<T> list) {
this._list = list;
}
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
// Implement List<T> interface:
public boolean add(T element) {
return _list.add(element);
}
public void add(int index, T element) {
_list.add(index, element);
}
// etc...
}
Alternatively, if the methods don't need to access protected members, then static helper methods are a less clucky alternative:
public class FilterUtils {
public static void retainAll(List<T> list, Class<?> c) {
//..
}
public static void removeAll(List<T> list, Class<?> c) {
//..
}
}
What prevents you from just adding new methods to the interface?
If you can't just add the new functionality to old interface, you could consider making another interface and then an implementation which merely implements those two. Just to be clear, in code this is what I mean:
// Old functionality:
public interface Traveling {
void walk();
}
// Old implementation:
public class Person implements Traveling {
void walk() { System.out.println("I'm walking!"); }
}
// New functionality:
public interface FastTraveling {
void run();
void fly();
}
// New implementation, option #1:
public class SuperHero extends Person implements FastTraveling {
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
// New implementation, option #2:
public class SuperHero implements Traveling, FastTraveling {
void walk() { System.out.println("I'm walking!"); }
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
I think it's illegal because you can not guarantee what class T will be. Also there are technical obstacles (parent's class name must be written in bytecode, but Generics information get lost in bytecode).
You can use Decorator pattern like this:
class ListDecorator implements List {
private List decoratingList;
public ListDecorator(List decoratingList){
this.decoratingList = decoratingList;
}
public add(){
decoratingList.add();
}
...
}
class FilterByArrayList extends ListDecorator {
public FilterByAbstractList () {
super(new ArrayList());
}
}
There is a delegation/mixin framework that allows a form of this. You can define a new interface, implement a default implementation of that interface, then request classes which implement that interface but subclass from elsewhere in your hierarchy.
It's called mixins for Java, and there's a webcast right there that demonstrates it.
I'm afraid it's not clear what do you want to get.
Basically, I don't see any benefit in using 'public class NewFunctionality<T extends OldFunctionality> extends T' in comparison with 'public class NewFunctionality extends OldFunctionality' ('public class FilterByType<T extends List> extends T' vs 'public class FilterByType<T> implements List<T>')

Categories

Resources