As the others have said, if you intend to access the method statically, you do not need an instance, and therefore you do not need a parameter in TestClass#getName at all. If you do want it to be an instance method, however, you can do one of three things:
1) Take in the type TestClassTwo in TestClass#getName:
public class TestClass {
public void getName(TestClassTwo obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String name = obj.getTwoName();
// Do something with 'name'
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
TestClass tc=new TestClass();
tc.getName(new TestClassTwo());
}
}
2) Cast the object to an instance of TestClassTwo, checking the type:
public class TestClass {
public void getName(Object obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if (obj instanceof TestClassTwo) {
TestClassTwo two = (TestClassTwo) obj;
String name = two.getTwoName();
// Do something with 'name'
} else {
// Handle failure accordingly (throw an exception, log an error, do nothing, etc.)
}
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
TestClass tc=new TestClass();
tc.getName(new TestClassTwo());
}
}
3) If you want to allow other classes to have a getTwoName() function, define an interface and take an instance of that interface as a parameter to TestClass#getName:
public interface HasTwoName {
public String getTwoName();
}
public class TestClassTwo implements HasTwoName {
@Override
public String getTwoName() {
return "2nd";
}
}
public class TestClass {
public void getName(HasTwoName obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String name = two.getTwoName();
// Do something with 'name'
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
TestClass tc=new TestClass();
tc.getName(new TestClassTwo());
}
}