The Base class will receive an unknown data structure via Data type. The Derived class needs to override the printObj method in order to print the content of the Data type object. For this example, the Data type object contains one field which is a string. How to override the printObj() to print the content of String message variable?
// generic class
public abstract class Base <T>{
T obj;
public Base(T t){
obj = t;
}
public T getObject(){
return obj;
}
public void setObject(T t){
obj = t;
}
public abstract void printObj();
}
// specific class
public class Derived<T> extends Base<T>{
public Derived(T t) {
super(t);
}
@Override
public void printObj() {
//?????
}
}
// data can be changed
public class Data {
String message;
public Data(String msg){
message = msg;
}
}
// application class
public class App {
public static void main(String[] args) {
Data d = new Data("Hello");
Derived<Data> dClass = new Derived<Data>(d);
dClass.printObj();
}
}
The T
in Derived<T>
could be anything, so the compiler doesn't know that it has a message
field. Maybe you wanted
public class Derived<T extends Data> extends Base<T>
then you could have
@Override
public void printObj() {
whatever(obj.message);
}
In computer programming , the strategy pattern (also known as the policy pattern ) is a software design pattern that enables an algorithm 's behavior to be selected at runtime.
The strategy pattern
You can solve this problem using above mentioned design pattern easily by using a simple interface
that separate out the printable functionality/algorithm . Any object of this type will be called the printable object .
interface Printable{public void print();}
Now it should be like this T extends Printable
that means any object of type Printable
abstract class Base<T extends Printable> implements Printable{...}
Now T extends Printable
so you can downcast it to Printable
and can call print()
method on it that will call the method of the passed printable object.
class Derived<T extends Printable> extends Base<T> {
...
@Override
public void print() {
((Printable)getObject()).print();
}
}
Here Data
is a printable object by simply implementing Printable
interface.
class Data implements Printable {
String message;
...
@Override
public void print() {
System.out.println(message);
}
}
Lets create one more class to understand the benefit of using this design pattern that's not possible by using T extends Data
.
class NonData implements Printable {
String message;
...
@Override
public void print() {
System.out.println(message);
}
}
Main class:
Data d = new Data("Hello");
Derived<Data> dClass = new Derived<Data>(d);
dClass.printObj(); // output Hello
NonData d1 = new NonData("Bye");
Derived<NonData> dClass1 = new Derived<NonData>(d1);
dClass1.printObj(); // output Bye
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.