question about java template

H

Hatter Jiang

can i write a java class like this:

public class MyPrintJob<T extends Printable> extends T {
public void call() {
print("hello");
}
}

of course the code above cannot be compiled.

public interface Printable {
public void print(String string);
}

public class APrinter implements Printable {
public void print(String string) {
System.out.println("This is A printer:" + string);
}
}

public class BPrinter implements Printable {
System.out.println("This is B printer:" + string);
}

then when i can :
MyPrintJob<APrinter> aPrinter = new MyPrintJob<APrinter>();
aPrinter.call();
// outputs: This is A printer: hello

and :
MyPrintJob<BPrinter> bPrinter = new MyPrintJob<BPrinter>();
bPrinter.call();
// outputs: This is B printer: hello
 
R

Roedy Green

public class MyPrintJob<T extends Printable> extends T {
public void call() {
print("hello");
}
}

The type erasure principle is , once generics are handled there is no
trace of them left in the object code. "extends T" would have to
have an effect on the object code, so it would have to be illegal.
 
L

Lew

Hatter said:
can i write a java class like this:

public class MyPrintJob<T extends Printable> extends T {
public void call() {
print("hello");
}
}

of course the code above cannot be compiled.

What is the extra "extends T" supposed to accomplish?

Your example with APrinter and BPrinter as T doesn't show any subclass of
either APrinter or BPrinter, indeed, any relationship between the two at all.
 
D

Daniel Pitts

Hatter said:
can i write a java class like this:

public class MyPrintJob<T extends Printable> extends T {
public void call() {
print("hello");
}
}

of course the code above cannot be compiled.
Templates are a C++ thing, and quite different from Java Generics.
Don't try to think of them the same way, it is not helpful. In C++
templates get expanded for every use, in Java, Generics represent a
limited meta-type system. The Generic definitions/declarations only
affect compile time type information of references. "extends T" would
have to recompile the class MyPrintJob for every MyPrintJob<x> you
created, and that simply doesn't happen.

Hope this helps,
Daniel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top