I have these two classes
class 1 :
public class MyClass1
{
public void myClass1Print()
{
System.out.println("in myClass1Print");
}
}
class 2 :
public class MyClass2
{
public void myClass1Print()
{
System.out.println("in myClass1Print");
}
}
How can I create a generic method in class 3 so that the method takes the parameters as generic.
class 3 :
public class MyClass3
{
public static void main(String[] args)
{
MyClass3 obj3 = new MyClass3();
MyClass1 obj1 = new MyClass1();
MyClass2 obj2 = new MyClass2();
obj3.methodMyClass3(obj1, obj2);
}
public <T> void methodMyClass3(T exp,T act)
{
System.out.println("obj1===>>>"+exp.myClass1Print());// compilation error
System.out.println("obj2===>>>"+act.myClass2Print());// compilation error
}
}
since the arguments exp and act are not considered as Objects of MyClass1 , MyCLass2
thus Compilatin error is
The method myClass1Print() is undefined for the type T
The method myClass2Print() is undefined for the type T
You have to use an Interface
#FunctionalInterface
public interface GenenericPrint {
void myClassPrint();
}
public class MyClass1 implements GenenericPrint {
#Override
public void myClassPrint(){
System.out.println("print something from Class1");
}
}
public class MyClass2 implements GenenericPrint {
#Override
public void myClassPrint(){
System.out.println("print something from Class2");
}
}
public class MyClass3{
public static void main(String[] args){
MyClass3 obj3 = new MyClass3();
GenenericPrint obj1 = new MyClass1();
GenenericPrint obj2 = new MyClass2();
obj3.methodMyClass3(obj1, obj2);
}
public void methodMyClass3(GenenericPrint exp,GenenericPrint act){
System.out.println("obj1===>>>"+exp.myClassPrint());// no compilation error
System.out.println("obj2===>>>"+act.myClassPrint());// no compilation error
}
}
Related
I am trying to compile the code below:
class Good{
Good(){}
public void getJoke(){
System.out.println("Good joke: ...");
}
}
class Joke<T>
{
T obj;
Joke() { this.obj = new T(); }
public void getThisJoke() { this.obj.getJoke(); }
}
class GoodJoke extends Joke<Good>
{
GoodJoke(){
super();
}
}
class Main
{
public static void main (String[] args)
{
GoodJoke j = new GoodJoke();
j.getThisJoke();
}
}
But I am getting the error:
T extends Object declared in class Joke
prog.java:12: error: cannot find symbol
public T getThisJoke() { return this.obj.getJoke(); }
How can I tell Java that the generic type 'T' has a method called 'getJoke'?
Introduce an interface
interface Comedian {
void getJoke();
}
Make Good implement it
class Good implements Comedian {
//.. same
Make Joke take T as an parameter. There is no way it can instantiate it itself. Add a constraint that T must implement the interface.
class Joke<T extends Comedian>
{
T obj;
Joke(T obj) { this.obj = obj; }
public void getThisJoke() { this.obj.getJoke(); }
}
Pass Good as an argument to GoodJoke
public static void main (String[] args)
{
GoodJoke j = new GoodJoke(new Good());
Now it compiles https://ideone.com/lDhvdC
I'm new in java, I want to call method class from implemented Class with interface without know class name "ClassA", which only know Object c and I have 2 file.
File (1) CobaInterface.java
package cobainterface;
public class CobaInterface {
public static void main(String[] args) {
ImplementedClass implementedClass = new ImplementedClass();
ClassA clsA = new ClassA();
implementedClass.myMethodFromClassA(clsA);
}
}
class ClassA{
public Integer getTwo(){
return 2;
}
}
interface MyInterface {
public void myMethod();
//here interface
public void myMethodFromClassA(Object c);
}
File (2) : ImpementedClass.java
package cobainterface;
public class ImplementedClass extends CobaInterface {
public void myMethodFromClassA(Object c) {
//System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
}
}
How about if I want to call method getTwo() from ClassA without know Class Name, which only know Object c from file (2) as describe in code above. Thanks for advance.
You should use generic types so the implementation knows what the object will be,
interface MyInterface<T> {
public void myMethod();
//here interface
public void myMethodFromClassA(T c);
}
The impl becomes,
package cobainterface;
public class ImplementedClass Implements MyInterface<ClassA> {
public void myMethodFromClassA(ClassA c) {
//System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
}
}
All together,
class Scratch {
public static void main(String[] args) {
ImplementedClass implementedClass = new ImplementedClass();
ClassA clsA = new ClassA();
implementedClass.myMethodFromClassA(clsA);
}
}
class ImplementedClass implements MyInterface<ClassA> {
#Override
public void myMethod() {
}
#Override
public void myMethodFromClassA(ClassA c) {
System.out.println(c.getTwo());
}
}
class ClassA {
public Integer getTwo() {
return 2;
}
}
interface MyInterface<T> {
void myMethod();
void myMethodFromClassA(T c);
}
You could also do a cast
System.out.println((MyClass)c.getTwo());
but you will lose all benefit of type saftey.
Is there a way on "Rewriting" a function.
Pseudo:
function a() {print "B"}
function a() {print "C"}
Output: C
Overriding
class MyClass {
public void myMethod () {
System.out.println("MyClass");
}
}
class MySubClass extends MyClass {
#Override
public void myMethod () {
System.out.println("MySubClass");
}
public static void main (String[] args) {
MyClass a = new MyClass();
a.myMethod(); // "MyClass"
MySubClass b = new MySubClass();
b.myMethod(); // "MySubClass"
}
}
In this example, MySubClass overrides the inherited method myMethod.
Overloading
class MyClass {
public void myMethod () {
System.out.println("myMethod");
}
public void myMethod (int i) {
System.out.println(i * 2);
}
public void myMethod (String s) {
System.out.println("Hello, " + s);
}
public static void main (String[] args) {
MyClass a = new MyClass();
a.myMethod(); // "myMethod"
a.myMethod(33); // "66"
a.myMethod("Jeremy") // "Hello, Jeremy"
}
}
In this example, MyClass has multiple definitions of the method myMethod, but they accept different arguments.
Simply rewrite the method in its subclass.
public class Something {
public Something() {
}
public void printHi() {
System.out.println("Hi");
}
}
public class SomethingElse extends Something {
public SomethingElse() {
}
public void printHi() {
System.out.println("I refuse to say hi!");
}
}
Something something = new Something();
something.printHi(); // prints Hi
SomethingElse somethingElse = new SomethingElse();
somethingElse.printHi(); // prints I refuse to say hi!
Consider the following classes
Class A{
public void m1(){
System.out.println("test in A.m1()");
}
public void m2(){
//do something a
}
}
Class B{
public void m1(){
//do something b
}
public void m2(){
//do something b
}
}
Class C{
public void m1(){
//do something c
}
public void m2(){
//do something c
}
}
Class T{
public void m3(Object obj1){
obj1.m1();
}
public void m4(Object obj1){
A a=new A();
m3(a);
}
}
So now my question is, is there any way I can send an open object to a method which will detect what type of object it is and call method of that object class. In this example I am hoping to see the output: "test in A.m1()"
You can use Java's Reflection API to query an arbitrary object to see if it has a method named m1 or m2 and then invoke it. But that is pretty ugly.
Is there anything from stopping you using an interface? Example below (where "..." indicates places where you would put your specific implementation):
interface MyMethods {
public void m1();
public void m2();
}
class A implements MyMethods {
public void m1() { ... }
public void m2() { ... }
}
class B implements MyMethods {
...
}
class C implements MyMethods {
...
}
class T {
public void m3(MyMethods obj1) {
obj1.m1();
}
public void m4(Object obj1) {
// Call m3 three times with different object instance types...
A a = new A();
m3(a);
B b = new B();
m3(b);
C c = new C();
m3(c);
}
}
Consider the following program:
import java.util.List;
import java.util.ArrayList;
public class TypeTest {
public static class TypeTestA extends TypeTest {
}
public static class TypeTestB extends TypeTest {
}
public static final class Printer {
public void print(TypeTest t) {
System.out.println("T");
}
public void print(TypeTestA t) {
System.out.println("A");
}
public void print(TypeTestB t) {
System.out.println("B");
}
public <T extends TypeTest> void print(List<T> t) {
for (T tt : t) {
print(normalize(tt.getClass(), tt));
}
}
private static <T> T normalize(Class<T> clz, Object o) {
return clz.cast(o);
}
}
public static void main(String[] args) {
Printer printer = new Printer();
TypeTest t1 = new TypeTest();
printer.print(t1);
TypeTestA t2 = new TypeTestA();
printer.print(t2);
TypeTestB t3 = new TypeTestB();
printer.print(t3);
System.out.println("....................");
List<TypeTestB> tb1 = new ArrayList<TypeTestB>();
tb1.add(t3);
printer.print(tb1);
}
}
The main method now prints:
T
A
B
....................
T
What should I do to make it print the followings?
T
A
B
....................
B
I'd like to avoid writing a loop such as the following for each of the type that can be printed:
public void printTypeTestB(List<TypeTestB> t) {
for (TypeTestB tt : t) {
print(tt);
}
}
The root of your problem is that Java method overloads are resolved at compile time based on the declared type of the method argument expressions. Your program seems to be trying to use runtime dispatching to different method overloads. That simply doesn't work in Java.
The fact that you are using generics in your example is a bit of a red herring. You would have the same problem if you replaced the type parameter <T> with TypeTest.
Concider creating a visitor interface which knows about all relevant subtypes.
public class TypeTestFoo {
interface TypeTestVisitor {
void visit(TypeTestA t);
void visit(TypeTestB t);
void visit(TypeTest t);
}
interface TypeTest {
void accept(TypeTestVisitor visitor);
}
public static class TypeTestA implements TypeTest {
public void accept(TypeTestVisitor visitor) {
visitor.visit(this);
}
}
public static class TypeTestB implements TypeTest {
public void accept(TypeTestVisitor visitor) {
visitor.visit(this);
}
}
public static final class Printer implements TypeTestVisitor {
public void visit(TypeTestA t) {
System.out.println("A");
}
public void visit(TypeTestB t) {
System.out.println("B");
}
public void visit(TypeTest t) {
System.out.println("T");
}
}
public static void main(String[] args) {
Printer printer = new Printer();
TypeTest t1 = new TypeTest() {
public void accept(TypeTestVisitor visitor) {
visitor.visit(this);
}};
t1.accept(printer);
TypeTestA t2 = new TypeTestA();
t2.accept(printer);
TypeTestB t3 = new TypeTestB();
t3.accept(printer);
System.out.println("....................");
List<TypeTestB> tb1 = new ArrayList<TypeTestB>();
tb1.add(t3);
for (TypeTestB each : tb1) {
each.accept(printer);
}
}
}
This should print out what you wanted:
T
A
B
....................
B
The types are listed in the interface which allows for compile-time overloading. On the other hand, this is a single point where you have put the subtypes for which you wan't to parameterize behavior. Java is not a very dynamic language... :)
candidate for the convoluted "visitor pattern".
or simply move print() method from Printer to TypeTest