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;
}
}
}
Related
Can a innerclass also be a subclass. Also one more thing in this set of java planguage it's not allowing me to create a instance of subclass even though I already created a instance of my encapsulating class for the innerclass.
public class Main {
Main OpTypes[] = new Main[3];
public static void main(String[] args) {
Main c = new Main();
c.OpTypes[0] = new Division(6,3);
Jool x = new Jool();
}
public class Jool {
public Jool() {
}
}
}
If you try it, you'll find that an inner class can extend a class.
Also, since the inner class is not static, it requires an instance of the outer class when constructing it. In the code below, you'll see two ways of doing that.
Method test shows the most common way, which is to do it from an instance (non-static) method of the outer class, in which case the outer class is implicit.
Method main shows how to do it outside of an instance method of the outer class, in which case you have to give an outer class instance before the new operator.
class MyBaseClass {
}
class Main {
public static void main(String[] args) {
Main c = new Main();
Jool x = c.new Jool(); // "c" explicitly used as outer class instance
}
public void test() {
Jool x = new Jool(); // "this" implicitly used as outer class instance
}
public class Jool extends MyBaseClass { // Inner class extends unrelated class
}
}
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());.
What's the reason why - an enclosing instance that contains appears when trying to instantiate a class?
Below is my actual code:
public static void main(String[] args) {
InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type.Item_Type();
// Error: an enclosing instance that contains InterspecTradeItems_Type.Item_Type is required
}
public class InterspecTradeItems_Type {
public class Item_Type {
}
}
Thanks.
As Item_Type is inner class. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type().new Item_Type();
Since Item_Type class is not a static nested class, but an inner class of InterspecTradeItems_Type, you need an instance of the later to access the former.
So, to create an instance of the inner class, you should create instance of the enclosing class:
new InterspecTradeItems_Type().new Item_Type();
Of course another option is to make Item_Type a static class:
public class InterspecTradeItems_Type {
public static class Item_Type {
}
}
And then your code would work just fine.
Assuming InterspecTradeItems_Type is declared/defined in a class called Main, you need
InterspecTradeItems_Type.Item_Type item = new Main().
new InterspecTradeItems_Type().new Item_Type();
You have an inner class within and inner class. You need an instance of each outer class to get to it.
try
public static void main(String[] args) {
InterspecTradeItems_Type item = new InterspecTradeItems_Type();
Item_Type item1 = item.new Item_Type();
}
The correct way to have an object of inner class is
InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type.new Item_Type();
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
So either use above syntax or make Item_Type class static
public static void main(String[] args) {
InterspecTradeItems_Type.Item_Type item = new InterspecTradeItems_Type.
Item_Type();
// Error: an enclosing instance that contains
InterspecTradeItems_Type.Item_Type is required
}
public class InterspecTradeItems_Type {
public static class Item_Type {
}
}
Read docs on Inner classes for more information.
If I have an inner class e.g.
class Outer{
class Inner{}
}
Is there any way to check if an arbitrary Object is an instance of any Inner, regardless of its outer object? instanceof gives false when the objects are not Inners from the same Outer. I know a workaround is just to make Inner a static class, but I'm wondering if what I'm asking is possible.
Example:
class Outer{
Inner inner = new Inner();
class Inner{}
public boolean isInner(Object o){
return o instanceof Inner;
}
}
Outer outer1 = new Outer();
Outer outer2 = new Outer();
boolean answer = outer1.isInner(outer2.inner); //gives false
And what about?
public static boolean isInnerClass(Class<?> clazz) {
return clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers());
}
The method isMemberClass() will test if the method is a member (and not an anonymous or local class) and the second condition will verify that your member class is not static.
By the way, the documentation explains the differences between local, anonymous and nested classes.
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
o instanceof Outer.Inner gives false when o is an instance of an Inner of any Outer other than the one you're calling it from.
This doesn't happen for me - I get true for o instanceof Inner regardless of which particular enclosing instance of Outer the o belongs to:
class Outer {
class Inner {}
void test() {
// Inner instance that belongs to this Outer
Inner thisInner = new Inner();
// Inner instance that belongs to a different Outer
Outer other = new Outer();
Inner otherInner = other.new Inner();
// both print true
System.out.println(thisInner instanceof Inner);
System.out.println(otherInner instanceof Inner);
}
public static void main(String[] args) {
new Outer().test();
}
}
Tested with both Java 6 and 7.
Did you try using getEnclosingClass():
Returns the immediately enclosing class of the underlying class. If the underlying class is a top level class this method returns null.
Outer.class.equals(object.getClass().getEnclosingClass())
Getting the correct enclosing class of the object , IMHO is not so easy . Read this.
Somewhat of a hack would be :
object.getClass().getName().contains("Outer$");
you could always:
getClass().getName()
and do a String comparison.
EDIT : to account for inheritance (among inner classes? who would do that?!) you could always loop through getSuperclass() and check for them as well, and even go after implemented interfaces.
The java.lang.Class.getEnclosingClass() method returns the immediately enclosing class of the underlying class. If this class is a top level class this method returns null.
The following example shows the usage of java.lang.Class.getEnclosingClass() method:
import java.lang.*;
public class ClassDemo {
// constructor
public ClassDemo() {
// class Outer as inner class for class ClassDemo
class Outer {
public void show() {
// inner class of Class Outer
class Inner {
public void show() {
System.out.print(getClass().getName() + " inner in...");
System.out.println(getClass().getEnclosingClass());
}
}
System.out.print(getClass().getName() + " inner in...");
System.out.println(getClass().getEnclosingClass());
// inner class show() function
Inner i = new Inner();
i.show();
}
}
// outer class show() function
Outer o = new Outer();
o.show();
}
public static void main(String[] args) {
ClassDemo cls = new ClassDemo();
}
}
Output
ClassDemo$1Outer inner in...class ClassDemo
ClassDemo$1Outer$1Inner inner in...class ClassDemo$1Outer
I was googling for finding out better answers, to find out that there are none out there.
Here is what I have which works pretty well:
public static boolean isStatic(Class klass) {
return Modifier.isStatic(klass.getModifiers());
}
/**
* Non static inner class
*/
public static boolean isInnerclass(Class klass) {
return klass.getDeclaringClass() != null && !isStatic(klass);
}
Will return true for local inner classes. isMemberClass and others do not work for this purpose.
Here is basically what I have:
public class Game extends Activity{
public class Work{
public class Shuffle{
*Class I need to access*
}
}
}
Here is the class I will be accessing Shuffle from:
public class Deck extends Game {
public int shuffle() {
//WHAT DO I NEED TO DECLARE HERE IN ORDER TO ACCESS Shuffle.getShuffle()?
int[] shuffDeck = (MY SHUFFLE CLASS).getShuffle();
int x = shuffDeck[i];
String y = String.valueOf(x);
i += 1;
return x;
}
}
What do I need to declare to be able to access Shuffle.getShuffle() in my Deck class?
Now taking of Nested Classes its of 2 types :
1. Inner Classes (Non-static)
2. Top Level Classes (static)
- Inner Class (Non-static) has an Implicit Reference to its Outer Class (Enclosing Class).
To access an Inner Class from outside you need to access it using the Outer Class Object.
Eg:
public class Outer{
class Inner{
}
}
public class Test{
public static void main(String[] args){
Outer o = new Outer();
Outer.Inner i = o.new Inner();
}
}
- A Top-Level Class (static) is just like a separate class in the Outer Class.
Top-level class needs to create an object of the Outer Class to access its Non-static members, but It can Access the Static methods and Static variables of the Outer class directly.
Eg:
public class Outer{
class Inner{
}
}
public class Test{
public static void main(String[] args){
Outer.Inner i = new Outer.Inner();
}
}
You cant access Inner class methods, and fields, from outer classes, directly. However you can access outer class methods, inside inner classes.
To access inner classes, you need to create an object of inner class, than only you can access inner class fields. See nested classes for more clarifications:
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
You are talking about nested classes, try to read also this article. Maybe it can help.
http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes
A nested class should exist only to server outer class. You should not expose inner classes to outside world.
public class Game extends Activity{
public static class Shuffle
{
// provide shuffle method here which will use internal implementation of
// shuffle.
}
int[] shuffle()
{
// call inner class method from here. Also declare inner class as
// static since I guess your inner class does not require instance
// of outer class.
return null;
}
And access shuffle() method of Game using Object of Game
int[] shuffDeck = (Game object).getShuffle();
public class Outer{
class Inner{
}
}
Outer.Inner art = (new Outer()).new Inner();
import android.content.Context;
import android.widget.Toast;
public class Outer{
private Context context;
public Outer(Context con) {
context = con;
String text = "Hello, I'm dbManager.";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration ).show();
}
public class Inner{
public Inner() {
String text = "Hello, I'm «Art dbManager».";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration ).show();
}
}
}
Outer.Inner art = (new Outer(this)).new Inner();