Java how to access a class within a class - java

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

Related

How to extends Abstract Inner Class in java

I confused if
Abstract Class A{method();method2();}
And Other Class B Which Have Inner Class C
Class B{Abstract Class C{method(){//body}}}
And now Question is how to extends Class C b/C Abstract Class must be extends else
this is Unused class.
First, let's make it simpler - this has nothing to do with Android directly, and you don't need your A class at all. Here's what you want:
class Outer {
abstract class Inner {
}
}
class Child extends Outer.Inner {
}
That doesn't compile, because when you create an instance of Child you need to provide an instance of Outer to the Inner constructor:
Test.java:6: error: an enclosing instance that contains Outer.Inner is required
class Child extends Outer.Inner {
^
1 error
There are two options that can fix this:
If you don't need to refer to an implicit instance of Outer from Inner, you could make Inner a static nested class instead:
static abstract class Inner {
}
You could change Child to accept a reference to an instance of Outer, and use that to call the Inner constructor, which uses slightly surprising syntax, but works:
Child(Outer outer) {
// Calls Inner constructor, providing
// outer as the containing instance
outer.super();
}
Note that these are alternatives - you should pick which one you want based on whether or not the inner class really needs to be an inner class.
You simply extend it
class B{abstract class C{abstract void method();}}
class D extends B{
class E extends C{
void method(){
System.out.println("Hello World");
}
}
}
Or slightly more complicated without extending outer class
class B{abstract class C{abstract void method();}}
public class F extends B.C{
F(B b){
b.super();
}
void method(){
System.out.println("Hello World");
}
public static void main(String[] args){
B b = new B();
F f = new F(b);
f.method();
}
}

Instantiate subclass of abstract class

how do I instantiate the sub class of an abstract class? it gives error -- no enclosing instance of type abstractclass is accessible. no matter how I interchange the values. I know I cant use motorvehicle cuz abstract class cant be instantiated....
public class abstractclass {
public static void main(String args[]){
Car car1 = new Car();
}
abstract class MotorVehicle
{
int fuel;
int getFuel()
{
return this.fuel;
}
abstract void run();
}
class Car extends MotorVehicle
{
void run()
{
System.out.print("Wrroooooooom");
}
}
}
It won't let you instantiate them because you've declared them as inner classes. Precede the class declarations with static and you'll be able to do it:
class Outer {
class Inner {
}
static class Nested {
}
}
If a nested class is inner (non-static), it belongs to instances of the outer class, not the outer class itself. Inner classes need an instance of the outer class to be instantiated. Static nested classes do not.
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Outer.Nested nested = new Outer.Nested();
See Nested Classes tutorial. That is what the "no enclosing instance" message is about. You are right that an abstract class can't be instantiated directly, but Car isn't abstract.
Hi Here Car class is an inner class for abstractclass. so you can instantiate inner class like this only if its declared as static
Let's change your Program:
public class Abstract {
public static void main(String args[]){
Car car1 = new Car();
}
abstract class MotorVehicle
{
int fuel;
int getFuel()
{
return this.fuel;
}
abstract void run();
}
static class Car
{
void run()
{
System.out.print("Wrroooooooom");
}
}
}
Here Car class i declared as static and it can be instantiated inside "abstractclass".
For further reference you can look into Getting a "No enclosing instance of type..." error
Remove this:
public class abstractclass {
And also ending } from end of the file.
You have wrapped your whole program into one abstract class. Thats just wrong :).

The difference of static and non-static inner classes?

I was reading Effective Java 2 - Item 22 and it says in the title:
"Favor static member classes over non-static"
but at the end of the chapter
Implementations of the collection interfaces, such as Set and List,
typically use nonstatic member classes to implement their iterators:
// Typical use of a nonstatic member class
public class MySet<E> extends AbstractSet<E> {
... // Bulk of the class omitted
public Iterator<E> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<E> {
...
}
}
I made a test program to see if there is any difference between them and here it is.
public class JavaApplication7 {
public static void main(String[] args) {
// TODO code application logic here
JavaApplication7 t = new JavaApplication7();
Inner nonStaticObject = t.getAClass();
Sinner staticObject = new JavaApplication7.Sinner();
nonStaticObject.testIt();
staticObject.testIt();
}
public Inner getAClass(){
return new Inner();
}
static class Sinner{
public void testIt(){
System.out.println("I am inner");
}
}
class Inner{
public void testIt(){
System.out.println("I am inner");
}
}
}
The output is
I am inner
I am inner
So, they did the same job.
I wonder Why non-static class is used in this example?
An iterator usually needs to refer to the collection used to create it in the first place. You can do that with a static nested class which is explicitly provided with a reference to the collection - or you can just use an inner class, which has that reference implicitly.
Basically, if every instance of the nested class needs an instance of the enclosing class to operate (and that instance doesn't change), then you might as well make it an inner class. Otherwise, make it a static nested class.
the difference is that non-static inner class have an implicit reference to the containing class.
public class JavaApplication7 {
//You can access this attribute in non-static inner class
private String anyAttribute;
public Inner getAClass(){
return new Inner();
}
static class Sinner{
public void testIt(){
//Here, you cannot access JavaApplication7.this
}
}
class Inner{
public void testIt(){
//Here, you can access JavaApplication7.this
//You can also access *anyAttribute* or call non-static method getAClass()
}
}
}
The difference between static and non-static nested classes is that the non-static ones are implicitly associated with an instance of the outer class, which they can refer to as OuterClassName.this. This reference is useful when implementing iterators, as they need access to the members of the collection they are related to. You could achieve the same thing by using a static nested class which is explicitly handed a reference to the outer class.
there is no such thing as a static inner class, It is static nested class. "Each instance of a nonstatic [nested] class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance."
A static nested class does not have access to the enclosing instance.
reference: this so thread
In the case of creating instance, the instance of non s
static inner class is created with the reference of
object of outer class in which it is defined……this
means it have inclosing instance …….
But the instance of static inner class
is created with the reference of Outer class, not with
the reference of object of outer class…..this means it
have not inclosing instance…
For example……
class A
{
class B
{
// static int x; not allowed here…..
}
static class C
{
static int x; // allowed here
}
}
class Test
{
public static void main(String… str)
{
A o=new A();
A.B obj1 =o.new B();//need of inclosing instance
A.C obj2 =new A.C();
// not need of reference of object of outer class….
}
}

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

Compiler errors when static abstract Inner class accesses outer class private fields java

I have a class with private fieds and also a static abstract inner class with the generic type extending the outer class type, that tries to access the outer class private fields but get's the following error:
- error: a has private access in Outer
- error: doSomething has private access in Outer
See code below:
public abstract class Outer extends SomeOuter
{
private Object a;
private void doSomething(){}
public static absract class Inner<T extends Outer> extends SomeOuter.SomeInner<T> {
public InnerMethod(T p) {
p.a; //error: a has private access in Outer
p.doSomething() //error: doSomething has private access in Outer
}
}
}
I'm compiling using jdk 1.7
Can anyone please tell me why am getting this error.
An Inner class can access private field of enclosing class and a static inner class can also access any private members of enclosing class .
The class itself isn't really "static"; there's no such thing as a static class. The
static modifier in this case says that the nested class is a static member of the outer
class. That means it can be accessed, as with other static members, without having
an instance of the outer class.
Since it is a static member , it is able to access outer class's private members , because within class private members are accessible.
eg.
class One
{
private int i=0;
class Two
{
void go()
{
System.out.println(new One().i); //accessible
}
}
}
class two
{
private int i=3;
static class one
{
void go()
{
System.out.println(new two().i); //accessible in static class
}
}
}
But here ,
Inner<T extends Outer> extends SomeOuter.SomeInner<T>
T is a class which extends Outer , doesn't mean it is inner.
That why it is giving error.
thats how private modifier works if you ever declare any method or variable as private than that things can not be accessed out side the class
A static embedded class is effectively an outer class. It can't access the private members of another class. See the accepted answer to:
Static nested class in Java, why?
Both the Object and the function you're trying to use are declared as private, which means they cannot be used outside the Object. If you want to use them in child classes as well, declare them as protected.
Changes the scope of the fields on the Outer class to protected so that classes extending Outer may access these fields.
public abstract class Outer extends SomeOuter
{
protected Object a;
protected void doSomething(){}
public static absract class Inner<T extends Outer> extends SomeOuter.SomeInner<T> {
public InnerMethod(T p) {
p.a; //error: a has private access in Outer
p.doSomething() //error: doSomething has private access in Outer
}
}
}
Thats what you have private modifier for. Though it is the inner class, it cannot access the private members of the outer class. So, declare it as protected, as you are extending the outer class to inner class

Categories