Call inner class member from a different class - java

Please forgive me if this question is silly as i'm completely new to JAVA program. I'm looking into nested classes concept and come across the following program.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("Display: outer_x = " + outer_x);
}
}
}
class NestedClass {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
// Inner inner = new Outer().Inner();
// inner.display();
}
}
And my doubt is how to access members of Inner class from NestedClass. In "Java - The complete reference", it is given that "You can, however, create an instance of Inner outside of
Outer by qualifying its name with Outer, as in Outer.Inner". But if i try to use it as,
Inner inner = new Outer().Inner();
inner.display();
it is throwing error. So please help me experts.

You need to create a new Inner instance by using the new keyword.
Inner inner = new Outer().new Inner(); // "new" keyword is required to create a new Inner instance.
If you do not have the import for import com.java.test.Outer.Inner; added, add it. Or else, you can do something like this
Outer.Inner inner = new Outer().new Inner();

Outer st = new Outer();
Outer.Inner fl = st.new Inner();
Note that the code above would be exactly the same whether the main() method is inside the outer class (because main is a static method) or even in some other class. Some other class could only run the code if it has access to outer class . But, Outer Class will have default, or package access since access modifiers are not specified when Outer Class is declared. This essentially means that any class within the same package as OuterClass will be able to run the code above without any issues.

You first have to create an instance of the outer class. After that, you can create an instance of that nested inner class by the outer class' instance.
Outer outer = new Outer();
Outer.Inner a = outer. new Inner();
a.display();

Inner class can be accessed only through live instance of outer class.
Try this:
class NestedClass {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}

Use this:
Outer.Inner inner=new Outer().new Inner();
as you need to create object of Inner class too as it is not static inner class.
So your code becomes:
class NestedClass {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}

Related

Is Inner Class inherited to subClass of OuterClass?

I tried below code and according to it I have the understanding that inner class is inherited to OuterClass's subclass.Is it correct?
class Outter{
int i=1;
class Inner{
int i=2;
public void hello(){
System.out.println("hello from outter.inner");
}
}
}
class ChildClass extends Outter{
class ChildInner{
}
}
public class Classes {
public static void main(String[] args) {
Inner inner = (new ChildClass()).new Inner();
System.out.println(inner.i);
inner.hello();
}
}
Output as excepted:
2
hello from outter.inner
Inner inner = (new ChildClass()).new Inner();
As this line of code worked it should mean that Inner class is inherited to ChildClass
I am getting confused because of the below statement I found on Link
When an outer class is extended by it’s sub class, Member inner classes will not be inherited to sub class. To use inner class properties inside the sub class of outer class, sub class must also have an inner class and that inner class must extend inner class of the outer class.
So I will illustrate that statement with an example:
When an outer class is extended by it’s sub class, Member inner
classes will not be inherited to sub class. To use inner class
properties inside the sub class of outer class, sub class must also
have an inner class and that inner class must extend inner class of
the outer class.
class Outter {
void method(){
Inner test=new Inner();
test.i=5; //No problem to do that even if i is private because it is inner class
}
class Inner {
private int i = 2;
}
}
class ChildClass extends Outter{
void method2(){
Inner test=new Inner();
test.i=5; //Does not compile
}
}
You cannot access "i" in the child class. And if you also extend the inner there you can:
class ChildClass extends Outter{
void method2(){
Inner2 test=new Inner2();
test.i=5; //Compiles fine because we have also extended the inner class (like written in the quoted text)
}
class Inner2 extends Inner{ }
}
The statement:
Inner inner = (new ChildClass()).new Inner();
Is not really inherited to ChildClass
If you break it you are basically doing this:
ChildClass child = new ChildClass();
Inner inner = child.new Inner();
Now you can call new Inner() on the ChildClass because it extends Outter
This doesn't mean that ChildClass can call any of the methods/properties inside Inner just because Inner is part of Outter

Using a non static data member in to a non static nested class withourt using object

class Outer
{
int x=10;
class Inner
{
void show()
{
System.out.println(x);
}
}
public static void main(String args[])
{
Outer obj=new Outer();
Inner obj1=new Outer().new Inner();
obj1.show();
}
}
I tried making a non static nested class and tried to use non static data member of outer class in non static inner class. I did not get that if x is non static, how i am using it without object. Kindly give me the answer?
You're not using it without an object. Inner (non-static nested) classes have a reference to the outer object, whose x is used.
Inner class is just a syntactic sugar to have an implicit reference to an outer class. Internally (after javac compilation) your class Inner looks like this:
static class Inner
{
private final Outer this$0;
public Inner(Outer outer) {
this$0 = outer;
}
void show()
{
System.out.println(this$0.x);
}
}
And when you write Inner obj1=new Outer().new Inner(); the compiler changes it to something like Inner obj1=new Inner(new Outer());.

Android & Java inner class concept

i followed the link http://developer.android.com/reference/android/app/AlertDialog.html and i try to create new AlertDialog like this
AlertDialog myAlertDialog = new AlertDialog.Builder(MainActivity.this).create();
as per the document AlerDialog is the outerclass and Builder is the inner class within AlertDialog. Now i linked the same concept with java in accessing the inner class like this Outer myOuter2 = new Outer.Inner(); this piece of gives error when i try to access, here is the complete java code
package com.test;
public class Outer {
public void OuterMethod() {
System.out.println("OuterMethod");
}
public static void main(String[] args) {
Outer myOuter = new Outer();
myOuter.OuterMethod();
Outer myOuter2 = new Outer.Inner();//this piece of code gives error
}
class Inner {
Inner() {
System.out.println("constructor Inner");
}
public void InnerMethod() {
System.out.println("Inside InnerMethod");
}
}
}
so my question over here is how to understand the same inner class concept in android and accessing the methods within that
You have created an inner non-static class (an inner instance class), whereas AlertDialog.Builder is a static class.
To get your code to work as is you need an interesting way of invoking new that goes like this:
Outer.Inner myOuter2 = myOuter.new Inner();
This is because it acts much like any other non-static field within Outer - it requires an instance of Outer in order to be valid. In any event, this is often not a good idea as public inner non-static classes are rare.
More likely you want Inner to be a static class, i.e. one declared as:
static class Inner {
Essentially this decouples Inner from its containing class, it just happens to live inside it and so can be instantiated via new Outer.Inner(). It could happily live as a public class in its own right in a new .java file instead.
Inner static classes are useful when the inner class is only used in relation the outer class, so it shows the relationship between them.
In Android's case you use an AlertDialog.Builder only when building an AlertDialog. If it was a general Builder used by other classes (e.g. a plain Dialog) is would have instead been declared as its own public class (i.e. a standalone class that is not nested inside another).
There is no relationship between Outer and Inner except that they share a class file. Hence, you cannot type:
Outer myOuter2 = new Outer.Inner();
Perhaps you meant:
Outer.Inner myInner = new Outer.Inner();
The Inner class will need to be declared as static for this to work.
Note that a normal builder will return a type that is equal to the enclosing type. Here's a small example using similar class names to your code:
public class Outer {
public static void main(String[] args) {
Outer outer = new Outer.Builder().withParam("foo").build();
}
private final String someParam;
private Outer(String someParam) {
this.someParam = someParam;
}
public static class Builder {
private String someParam;
public Builder() {
}
public Builder withParam(String value) {
this.someParam = value;
return this;
}
public Outer build() {
return new Outer(someParam);
}
}
}
You may also wish to read Item #2 of Joshua Bloch's Effective Java, 2nd Edition for a good description of builder design and rationale. Available online: here.
Your inner class is non static type.
We should first create instance of your outer class:
Outer o=new Outer();
Outer.Inner oi=o.new Inner();
This is the basic way of create non static inner class object.
Suppose if your inner is of type static (i.e. static class Inner{....}),
then for creating object:
Outer.Inner oi=new Outer.inner();
The AlertDialog.Builder class is a static inner class as you can see here.
public static class Builder {...}
Finally i figured out here is the code
package com.test;
public class Outer {
public void OuterMethod() {
System.out.println("OuterMethod");
}
public static void main(String[] args) {
Outer myOuter = new Outer();
myOuter.OuterMethod();
Outer myOuter2 = new Outer.Inner().InnerMethod();
}
static class Inner {
Inner() {
System.out.println("constructor Inner");
}
public Outer InnerMethod() {
Outer myOuter = new Outer();
System.out.println("Inside InnerMethod");
return myOuter;
}
}
}

java inner classes method access

I have an outer class. I also have a private inner class that extends JPanel. This is the design of the code.
public class Outer{
private class Inner extends JPanel{
public void doSomeWork(){}
}
public Outer(){
Inner inner = new Inner();
inner.doSomeWork();
}
public static void main(String args[]){
Outer outer = new Outer();
}
}
I am not being able to access the doSomeWork() method of the inner class from the outer class. Please help.
Here is how you make an object of inner and access its variables...
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.doSomeWork();
Example code from Oracle is here...

Nested class(static inner) lifetime/scope

I declared a Static Inner class, of which I am creating a new instance in a method of Outer class. But, I am getting result suggesting that the same instance of Inner class is used everytime in my method.
Example Below,
public class Outer{
public method m(){
Inner n = new Inner(); //Creating local instance of Nested class
n.something();
}
public static class Inner{
Map<K,V> cache = new Map<K,V>();
void something(){
//use and update cache;
}
}
}
public Test{
public static void main(String a[]){
Outer o = new Outer();
o.m();
o.m(); //cache was still available
}
}
Can someone help with why two instance of Inner class are not created?
Also, should this behaviour change if I remove static from inner class?
static inner classes can be instantiated only once per outer enclosing class instance.Since you have only one Outer o = new Outer(); outer instance o.m(); will call same instance of inner class.
Create two instances like this
Outer o = new Outer();
o.m();
Outer o1 = new Outer();
o1.m(); // will create new instance of inner
Regarding static key word
Nested classes can be: static and non-static. Nested classes that are declared static are s static nested classes. Non-static nested classes are called inner classes.
A static nested class does not have a reference to a nesting instance, so a static nested class cannot access non-static methods of an instance of the class in which it is nested.

Categories