Java inner class access variable in another inner class - java

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();
}
}
}

Related

call a method of nested interface from enclosing class

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....
}
}

Decorator pattern member variable

I am implementing my first Decorator pattern. The base class which I want to decorate has a member variable initialized in the constructor. The decorated class also has this member variable (since it is a descendant of the base class). My question is, should I initialize this member variable in the decorated class too, or use the member variable of the base class (which lives inside the decorated class)?
Here is some code. I'm just curious whether Decorated1 or Decorated2 is better?
public class Base{
private String memberVariable;
public Base(){
memberVariable = "";
}
public Base(String s){
memberVariable = s;
}
public String Description(){
//code here
}
}
public abstract class BaseDecorator(){
public abstract String Description();
}
public class Decorated1 extends BaseDecorator{
Base b;
public Decorated1(Base _b){
b = _b;
}
public String Description(){
//code here
}
public String getMemberVariable(){
return b.getMemberVariable();
}
}
public class Decorated2 extends BaseDecorator{
Base b;
public Decorated1(Base _b){
super(_b.getMemberVariable());
b = _b;
}
public String Description(){
//code here
}
public String getMembervariable(){
return memberVariable;
}
}
You have to figure out what this variable means for your class, or if it is really needed, but i would suggest that no.
interface IObject{
//declare methods
void doSomething();
}
class ObjectA implements IObject{
private int variable;
public void doSomething(){
}
}
class DecorateObject implements IObject {
private IObject decoratedObject;
public void doSomething(){
decoratedObject.doSomething();
//do more things
}
}
if IObject is a drawable element, it would have x,y coordinates that would be inherited so it is correct to put on a superclass, in this case it would be an abstract class.
interface IObject{
//declare methods
}
abstract class AbstractObject implements IObject{
private int xCoordinate;
}
class ObjectA extends AbstractObject {
}
class DecorateObject extends AbstractObject {
private IObject decoratedObject;
}

How can you access public methods from private class from a different class in java?

I just have a question, is there any way to access public methods from a class which is private from a different class? For Example the print method can be accessed from a different class since the class is private?
private class TestClass {
public void print() {
}
}
Yes there is.
You don't actually return an direct reference to your private class, since other classes can't use it. Instead, you extend some public class, and return your private class as an instance of that public class. Then any methods it inherited can be called.
public interface Printable {
void print();
}
public class Test {
public Printable getPrintable() {
return new PrintTest();
}
private class PrintTest implements Printable {
public void print() {
}
}
}
Test test = new Test();
test.getPrintable().print();
You can do that by extending that class with a public class. Or you can always use reflection!

How to access a private nested class object of a sole class that uses it in java

I have a base class in Java. In that class I want to create a private class and I want to access the object of that private class in the base class. How can I do that?
Thanks in advance!
Do you mean this:
class Test {
private Inner inner = new Inner();
private class Inner {
public void foo() {}
}
// later somewhere
public void bar() {
inner.foo();
}
}
You can access an object of an inner class by creating it and remembering its reference. Just like an instance of any other class.
public enum Outer {;
private static class Nested {
private Nested() { }
}
public static Object getNested() {
return new Nested();
}
}
public class Main {
public static void main(String... args) {
System.out.println("I have an "+ Outer.newNested());
}
}
prints
I have an Outer$Nested#3f0ef90c
A good example is from Arrays. This creates an instance of a private nested class which implements a public interface which makes it useful.
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
/**
* #serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
PrivateClass c = new PrivateClass();
c.getSomeObject(); //??
You can use the above code in your base class; provided the private class is an inner class of your base class.
class Test {
private class Inner {
public void foo() {
System.out.println("vsahdashdashd");
}
}
// later somewhere
public void bar() {
new Inner().foo();
}
}
class javaapplication9 extends Test
{
public static void main(String[] args) {
Test inner = new Test();
inner.bar();
}
you can access private member from this type.

Can a method in an inner class access a parent class method?

I'm not sure if my question title describes my situation aptly, so my apologies if it doesn't! Anyway, let's say I have the following code snippet (visibility is as stated):
public class ChildClass extends ParentClass {
// more code
private void myMethod() {
MyClass mine = new MyClass() {
public void anotherMethod() {
// insert code to access a method in ParentClass
}
};
}
}
Is it possible for code within anotherMethod() to access a protected method found in ParentClass? If so, how can this be done?
I've tried something like...
(ParentClass.this).parentMethod();
...but obviously it doesn't work due to scope issues.
This compiles fine:
class MyClass {
}
class ParentClass {
protected void parentMethod() {
}
}
class ChildClass extends ParentClass {
private void myMethod() {
MyClass mine = new MyClass() {
public void anotherMethod() {
parentMethod(); // this works
}
};
}
}
A non-static inner class can access all methods of the enclosing class as if it were it's own methods:
public class Test {
public int getOne() {
return 1;
}
public class Inner {
public int getEnclosingOne() {
return getOne(); // this works...
}
}
}
A static inner class can not, as a static inner class is not bound to an instance of the parent class. That can only call static methods on the enclosing class.
As for methods when taking into account inheritance, an method in a non-static inner class can use all the methods of the enclosing (outer) class.
The interesting part is Test2.super.getOne() which indeed obtains getOne() from Test2.super, which is a Test. This is just like Test2 would access the method, namely using super though prefixed with Test2 to indicate you're accessing the namespace of the outer class.
public class Test2 extends Test {
public int getInnerOuterParentOne() {
Inner2 inner2 = new Inner2();
return inner2.getOuterParentOne();
}
public int getInnerOuterOne() {
Inner2 inner2 = new Inner2();
return inner2.getOuterOne();
}
public int getOne() {
return 2;
}
public class Inner2 {
public int getOuterOne() {
return getOne();
}
public int getOuterParentOne() {
return Test2.super.getOne();
}
}
public static void main(String[] args) {
Test2 test2 = new Test2();
System.out.println(test2.getInnerOuterOne()); // 2
System.out.println(test2.getInnerOuterParentOne()); // 1
}
}
There is no way to access "parent class method" in Java, irrelatively to visibility (except for super.parentMethod() in subclass's parentMethod()).
That is, if ChildClass overrides parentMethod(), there is no way to call ParentClass.parentMethod() (bypassing ChildClass.parentMethod()) from other methods of ChildClass.
However, if ChildClass doesn't override parentMethod(), that method is inherited by ChildClass, so that you can access it as a ChildClass's method, i.e. simply as parentMethod().

Categories

Resources