interface Example{
void methodExample();
}
class Y{
void do(Example x) { }
}
class X{
void methodX() {
Y y = new Y();
y.do(new Example() {
public void methodExample() {
System.out.println("methodExample");
}
});
}
}
I want to create a main class and call methodExample. How would I do that?
Since your class implements Example interface, and because void methodExample() is present on that interface, all you need to do is to reference the object by its interface, and call its method:
class Y{
public void doIt(Example x) {
x.methodExample();
}
}
The above works, because objects of all classes implementing Example, including all anonymous implementations, are known at compile time to implement methodExample().
If you don't have access to class Y then, the only way to do is to override doIt() itself first, using anonymous inner class and then, call the overridden method, e.g.:
class X {
void methodX() {
Y y = new Y() {
#Override
void doIt(Example x) {
x.methodExample();
}
};
y.doIt(new Example() {
public void methodExample() {
System.out.println("methodExample");
}
});
}
}
To call this, you can simply do:
public static void main(String[] args) throws Exception {
X x = new X();
x.methodX();
}
Related
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.
If there are 3 methods in
public class Hero extends GameCharacter {
public void test1(){};
public void test2(){};
public void test3(){};
is it possible while running this in
public class MainClass extends ApplicationAdapter implements InputProcessor {
#Override
public void create () {
private Hero mainHero;
For (int x = 0; x < 0; x++)
....
to run
mainhero.testx
?
This situation is suitable for Strategy Pattern. Basically you have a variation in functionality, so you create an interface for executing it, and create multiple implementations of it. It could look something like this:
package test;
public class Test {
public static interface TestStrategy {
void test();
}
public static class Test1 implements TestStrategy {
#Override
public void test() {
System.out.println("1");
}
}
public static class Hero {
TestStrategy test[] = new TestStrategy[]{
//either use defined class
new Test1(),
//or inline
() -> {System.out.println("2");}
};
}
public static void main(String[] args) {
Hero hero = new Hero();
for (int i = 0; i < hero.test.length; i++) {
hero.test[i].test();
}
}
}
You could using reflection, but you should evaluate better patterns for this.
Alternative solutions include
Conditionals
public void test(int x){
switch (x) {
case 1:
// Things for x == 1
break;
}
};
OOP, for when you have different types of Heroes
public abstract class Hero extends GameCharacter {
public abstract void test();
}
public class Hero1 extends Hero {
#Override
public void test() {}
}
...
List<Hero> heroes = ... ;
heroes.add(new Hero1());
for (Hero h : heroes) { h.test(); }
Or, just call all your test methods separately via independent unit-testing methods.
Like suggested before, you could use reflection for this. This example uses reflection to demonstrate that.
public void callYourClassMethod(String x) {
try {
YourClass yourClass = new YourClass()
Method method = YourClass.class.getDeclaredMethods("methodname" + x);
method.setAccessible(true); // Only needed if it's not accessible from calling class.
method.invoke(yourClass); // Assuming your method doesn't take any arguments.
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
System.err.println("Method methodname" + x + "is not declared.");
e.printStackTrace();
}
}
public class MyTest {
public static void main(final String[] args) {
B b = new B();
b.print();
}
}
class A {
private final int x = 5;
protected int getX() {
return x;
}
public void print() {
System.out.println(getX());
}
}
class B extends A {
private final int x = 10;
#Override
protected int getX() {
return x;
}
}
In this example, I need to print subclass value in the parent class.
It is working fine. No issue.
Now it is printing 10.
But I do not want to define that property in the parent class A.
Because in this example this x datatype is very simple. So no issue.
But in real-time I want to use other datatype which may be another Class variable or List<something> which have huge data.
So ultimately I do not wish to store that value in Class A.
Because it is redundant data. It will slow down in my Hibernate thing.
Please let me know, how to achieve this without declaring variable in parent class. But I still need to use subclass variable in parent class.
make abstract your class A and the getX(); method.
public class Test {
public static void main(final String[] args) {
B b = new B();
b.print();
}
}
abstract class A {
protected abstract int getX();
public void print() {
System.out.println(getX());
}
}
class B extends A {
private final int x = 10;
#Override
protected int getX() {
return x;
}
}
and override the toString method in place of your print method
#Override
public String toString() {
return String.valueOf(getX());
}
the final code
public class Test {
public static void main(final String[] args) {
B b = new B();
System.out.println(b);
}
}
abstract class A {
protected abstract int getX();
#Override
public String toString() {
return String.valueOf(getX());
}
}
class B extends A {
private static final int X = 10;
#Override
protected int getX() {
return X;
}
}
you could also define as static your x variable
But as say Andrew Tobilko you can consider also to use an interface if A doesn't represent a stateful entity.
It's certainly the best solution for your case, mix the use of an interface and an abstract class
public class Test {
public static void main(final String[] args) {
B b = new B();
System.out.println(b);
}
}
interface MyInterface {
int getX();
}
abstract class A implements MyInterface{
#Override
public String toString() {
return String.valueOf(getX());
}
}
class B extends A {
private static final int X = 10;
#Override
public int getX() {
return X;
}
}
You need the getX within the parent class, but you don't have information enough to implement this method there.
You can declare this class as abstract and mark the method with abstract as well. Doing that, you are handing the responsibility of method implementation over its subclasses and preventing from parent field declaration.
If the A doesn't describe any state (only actions/methods), you should consider replacing it with an interface. At the current state, it is the case.
You could make the parent class abstract, eliminate the property in the parent class, make getX() abstract, and then leave print() as concrete. Then just use the concrete implementation of getX() in the child class.
Suppose I have two classes A and B where A is a superclass of B. Now, I write a function (override), say funct() in both the classes. Then, if I want to call the funct() in A from an object of B, is it possible?
class A {
public void f() {...}
}
class B extends A {
#Override public void f() { super.f(); }
}
Is that what you want?
If instead you want to call A#f() directly on an instance of type B, you must provide a placeholder function for that:
class B extends A {
#Override public void f() { ... }
public void superF() { super.f(); }
}
new B().f(); // calls B#f();
new B().superF(); // calls A#f();
I have trick such as this situation to operate it in an illogical manner using Flag argument in funct() method :D, like this:
class A {
public void funct(boolean callSuper) {
// avoid using callSuper arg here
}
}
class B extends A {
#Override
public void funct(boolean callSuper) {
if (callSuper) {
super.funct(callSuper);
return;//if return type is void
} else {
//do here the functionality if the flag is false
}
}
}
or
class A {
public void funct() {
}
}
class B extends A {
private boolean callSuper = false;
#Override
public void funct() {
if (callSuper) {
super.funct(); // call A.funct() functionality
setCallSuper(false);
} else {
//do here the functionality of B.funct() if the flag is false
}
}
public void setCallSuper(boolean callSuper){
this.callSuper = callSuper;
}
}
Given classes like
class A {
public void funct() {...}
}
class B extends A {
#Override
public void funct() {...}
}
You ask
Then, if I want to call the funct() in A from an object of B, is it
possible?
So let's take
B b = new B();
b.funct();
A a = b;
a.funct();
((A)b).funct();
The above all do the same thing because of polymorphism and late-binding.
The only way to call the superclass' implementation is to get a reference to that member through the super keyword.
class A {
public void funct() {...}
}
class B extends A {
#Override
public void funct() {
super.funct();
}
}
class X
{
void method1(){}
void method2(){}
}
class Y
{
void someMethod()
{
/*
What is this type below called?
Anonymous class or
Anonymous-Inherited class or what???
*/
X xInstance = new X(){
#Override
void method1()
{
System.out.println("What kinda class is this ?");
}
}
}
}
It's an anonymous inner (or nested) class.
Reference: Local and Anonymous Inner Classes
X xInstance = new X(){
#Override
void method1()
{
System.out.println("What kinda class is this ?");
}
}
}
It is anonymous class. you have overriden implementation of method1()