call a method of nested interface from enclosing class - java

Let's suppose I have a class OuterClass which has a method classMethod() and an nested interface NastedInterface which in its turn has a method callback(). So how can I call the method of the interface callback() in the method of class classMethod()?
My goal is to be able to implement OuterClass.NastedInterface in other classes and do some operations in the callback() method, which will be called when the classMethod() will be called in OuterClass.
The code will look like something like this.
public class OuterClass {
public void classMethod(){
if(SOME_CONDITION){
\\ here I want to call the **callback()** method of **NastedInterface**
}
}
public interface NastedInterface {
void callback();
}
}
And the class that will implement this interface should look like something like this.
public class TestClass implements OuterClass.NastedInterface {
#Override
public void callback (){
DO SOMETHING....
}
}
Basically I want to create a callback mechanism, such as I have used many times in Android. For example the View.OnClickListener or all other such kind of ON_SOMETHINK_LISTENER s.
May be I am going in wrong direction, and I need to create such a mechanism in other way?

Put a member variable in your OuterClass that holds an instance of NestedInterface. Add a setter method that sets that variable, and make it public.
Make sure the check that the member isn't null before calling callback.

Outerclass needs to have a reference to the TestClass for this work.
So:
public class OuterClass {
private NastedInterface interfaceToCall;
public void classMethod(){
if(SOME_CONDITION){
\\ here I want to call the **callback()** method of **NastedInterface**
if(interfaceToCall != null)
{
interfaceToCall.callback();
}
}
}
public interface NastedInterface {
void callback();
}
}

Thanks to everyone for answers, I solved the problem and every answer here helped me in some way. But as the solution was not exactly how how suggested in answers, I will write it here for people who may need it in the future.
public class OuterClass {
private NastedInterface nastedInterface;
//In the constructor I am assigning the reference of the parent class
// of some other classes in my app which all may need to be notified when
// **callback()** has happened
public OuterClass(){
nastedInterface = TestClassParent.getInstance;
}
public void classMethod(){
if(nastedInterface != null){
nastedInterface.callback();
}
}
public interface NastedInterface {
void callback();
}
}
So here I have a class which will be the parent of some other classes and will implement NastedInterface.
public class TestClassParent implements OuterClass.NastedInterface {
private static TestClassParent instance;
public static TestClassParent getInstance(){
if(instance == null){
instance = new TestClassParent();
}
return instance;
}
#Override
public void callback(){
//I will override it in subclasses and do what I need in each class
}
}
And after this I can receive callback() event in any class that extends TestClassParent. For example:
public class TestClass1 extends TestClassParent {
#Override
public void callback (){
DO SOMETHING....
}
}
and
public class TestClass2 extends TestClassParent {
#Override
public void callback (){
DO SOMETHING ELSE....
}
}

Related

load method calls another method at the end in Java

I have an abstract class Task with two methods execute() and finish() as the following:
abstract class Task {
abstract void execute();
private void finish() {
// Do something...
}
}
How can I ensure that the overloaded method execute() in subclasses of Task implicitly calls finish() as the last statement?
I don't believe there is any way of 'forcing' sub-classes to invoke a method but you could try some sort of template method approach:
abstract class Foo {
protected abstract void bar(); // <--- Note protected so only visible to this and sub-classes
private void qux() {
// Do something...
}
// This is the `public` template API, you might want this to be final
public final void method() {
bar();
qux();
}
}
The public method is the entry-point and invokes the abstract bar and then the private qux method, this means that any sub-classes follow the template pattern. However it's no panacea of course - a sub-class could simply ignore the public method.
You can create a ExecutorCloseable class that implements the [AutoCloseable] interface, such as:
public class ExecutorCloseable extends Foo implements AutoCloseable
{
#Override
public void execute()
{
// ...
}
#Override //this one comes from AutoCloseable
public void close() //<--will be called after execute is finished
{
super.finish();
}
}
You could call it this way (silly main() example):
public static void main(String[] args)
{
try (ExecutorCloseable ec = new ExecutorCloseable ())
{
ec.execute();
} catch(Exception e){
//...
} finally {
//...
}
}
Hope it makes sense, I can't really know how you call these methods nor how you create the classes. But hey, it's a try : )
For this to work, the finish() method on Foo should be protected or public (first one recommended), though.

Java inner class access variable in another inner class

My main Class has 2 inner class, 1 of them is thread, I don't know how my inner class 2 can access (Or how to know var1 is true or false) value of inner class 1, this is my example, thanks!
public class InnerClass {
public class InnerClass1 implements NativeKeyListener {
public boolean var1;
}
public class InnerClass2 implements Runnable{
#Override
public void run() {
while (true) {
var1...
}
}
}
}
You cannot access nonstatic variables/methods/inner classes unless you have instantiated the object (i.e. created an instance of the object). You need an InnerClass1 object before you can store or get anything out of it. Until you do something like InnerClass1 foo = new InnerClass1(), there is no var1 anywhere.
Anyway, I think you are misusing inner classes. I'd suggest if you haven't already walking through the Java Tutorials Trail to get a basic idea of how classes, fields, and instantiation work in Java.
You can do it by an interface or class that is implemented by innerclass1. Try this:
public interface NativeKeyListener {
boolean a();
}
public class InnerClass {
static NativeKeyListener m() {
class InnerClass1 implements NativeKeyListener {
public boolean var1;
public boolean a() {
return var1;
}
}
return new InnerClass1();
}
public class InnerClass2 implements Runnable {
public void run() {
NativeKeyListener i = InnerClass.m();
i.a();
}
}
}

C# vs JAVA instance of Interface

I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :

Accessing inner hidden abstract class to get status updates

I want to invoke a private method which takes abstract class parameter and that abstract class is hidden (I can not access it directly). I need to get the updates whenever methods of abstract class are invoked by some other class.
Class I am refereeing to is:
public class A{
private void method(AbstractClassA object){ ... }
// please note below class is hidden. I can not do A.AbstractClassA . I have to access it using reflection unless there is any other way
public abstract class AbstractClassA {
//I am interested in getting this int whenever someone else calls the progressUpdate
public void progressUpdate(int update);
}
}
I am trying to access like this:
public class myClass{
Class<?> abstractClass = Class.forName("<package>.A$AbstractClassA");
A a = new A();
Method someMethod = a.getDeclaredMethod("method", (Class[])null);
someMethod.setAccessible(true);
someMethod.invoke(a, <something which I don't know>); //how to pass paramerts here so that I get all callbacks whenever progressUpdate is called by someone else and "update" parameter is changed.
}
public class SubClassA extends A {
private SubClassAbstractA subClassA;
public SubClassA() {
this.subClassA = new SubClassAbstractA();
}
public class SubClassAbstractA extends AbstractA {
#Override
public void progressUpdate(int update) {
SubClassA.this.progressUpdate(update);
}
}
public void progressUpdate(int update) {
//do things with int
}
public void someMethod() {
Class<?> clazz = A.class;
Method method = clazz.getDeclaredMethod("method");
method.setAccessible(true);
method.invoke(this, subClassA);
}
}

How to subclass this without repeating code

I have class Dad with subclass Son. I'd like to create a subclass of Dad and a subclass of Son that overrides a method of Dad.
What would be the best way of doing this without repeating code? I can not modify Dad and Son.
Given...
public class Dad {
public void doSomething() {}
}
public class Son extends Dad {
}
...I'd like to create...
public class DadSubclass extends Dad {
#Overrides
public void doSomething() {
// My code
}
}
public class SonSubclass extends Son {
#Overrides
public void doSomething() {
// My code
}
}
...without repeating // My code.
The obvious solution would be to create a helper class and call it for both, but this is problematic if I want to call protected methods, and I'm not allowed to create the subclasses with the same package.
Is there a better solution?
Create a common helper class and call it.
Assuming your code isn't accessing member variables, I would just put this code in a static utility class. If this isn't the case, you can still do this by passing in a common superclass - that of 'Dad' public static void mycode(Dad d). If you need specific variables in the subclasses themselves, I would rethink your class structure.
What you really want here is something like this:
class DadSonSubclass extends Dad, Son {
public void doSomething() {
//mycode
}
}
This is multiple inheritance, which is not supported by Java. So your only option would be to create a helper/utility class, which is perfectly acceptable. If you need to call protected methods, just pass the Dad object in to the helper class and create public callback methods to access this info.
Maybe better, maybe not, depending on your point of view, but it can certainly be done. Put your code into a helper class, and use a callback to give that helper access to the protected methods it needs:
interface Callback {
void foo();
void bar();
void one();
void two();
}
class Helper {
static void helpMe(Callback callback) {
// My code
}
}
class DadSubclass extends Dad {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
DadSubclass.this.foo();
}
public void bar() {
DadSubclass.this.bar();
}
public void one() {
throw new UnsupportedOperationException("one() doesn't exist in Dad");
}
public void two() {
throw new UnsupportedOperationException("two() doesn't exist in Dad");
}
});
}
}
class SonSubclass extends Son {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
SonSubclass.this.foo();
}
public void bar() {
SonSubclass.this.bar();
}
public void one() {
SonSubclass.this.one();
}
public void two() {
SonSubclass.this.two();
}
});
}
}

Categories

Resources