What are the 3 different contexts a class can be declared? - java

I am told there are three different contexts in which a class can be declared in Java.
It has to do with the location within a program, but I can't think of what they are.
Obviously a class can be declared at the top of a page, the only other example I can think of is like a nested class?
I feel I may be going about this the wrong way.

In a package
package com.example.mypackage;
public class TheClass {
}
In a class
package com.example.mypackage;
public class OuterClass {
class InnerClass {
}
}
Anonymously
public class MainClass {
public static void main(String[] args) {
AbstractClass myObject = new AbstractClass() {
// overrides and other fields of the
// anonymous class goes in this block
};
}
}
EDIT: As #daniu stated in the comment, a class can also be created in a method:
public class MainClass {
public static void main(String[] args) {
class MethodClass {
}
MethodClass myObject = new MethodClass();
}
}

There are actually 4 distinct syntactic contexts:
In the "compilation-unit" context; i.e. a top-level class declaration.
package foo;
public class Bar{}
As a nested class declaration in a class declaration.
package moo;
public class Cow {
public class Inner {}
}
As a nested class declaration in a method declaration.
package too;
public class Far {
public void test() {
class MethodInner{}
}
}
As an anonymous class declaration in a new expression. The expression could appear in a variety of contexts. For example:
package goo;
public class Tar {
public void test() {
Runnable r = new Runnable() {
public run() { }
};
}
}

This may be what you are looking for:
public class TopLevel {
public static void main(String[] args) {
TopLevel topLevel = new TopLevel();
Nested nested = new TopLevel.Nested();
Inner inner = topLevel.new Inner();
}
public static class Nested {
}
public class Inner {
}
}

Related

How to access anonymous inner class in main method?

How to access the anonymous inner class object in main method. It is giving compile time error saying that "cannot make static reference to non static method". If I am making anonymous inner class as static then I can access ut I want to access without making it static.
How to do that. Please help.
AnonymousInnerClass2.java
abstract class AnonymousInnerClass21
{
abstract void m();
}
public class AnonymousInnerClass2
{
AnonymousInnerClass21 a=new AnonymousInnerClass21()
{
#Override
void m() {
System.out.println("Hello");
}
};
public static void main(String[] args)
{
a.m();
}
}
this is because for accessing inner class (whether its is normal/named class or Anonymous class), you must create object of class in which inner class is defined, you can try below
abstract class AnonymousInnerClass21
{
abstract void m();
}
public class AnonymousInnerClass2
{
AnonymousInnerClass21 a=new AnonymousInnerClass21()
{
#Override
void m() {
System.out.println("Hello");
}
};
public static void main(String[] args)
{
AnonymousInnerClass2 anonymousInnerClass2= new AnonymousInnerClass2 ();//create outer class object
anonymousInnerClass2.a.m(); // access inner class object through outer class object
}
}

Nested Interafce in java

This is my java code:
class A {
interface That {
void show();
}
}
class B implements A.That {
public void show() {
System.out.println("Hi");
}
}
public class MainClass {
public static void main(String args[]) {
A obj = new A();
obj.That object = new B();
object.show();
}
}
Since A is a class (not abstract) we can create its instance and than we can use members of that instance. Now interface is member so obj.That should work but javac says that obj.That is not package. Why?
Interfaces are always static when nested in a class. You should therefore access your interface declaration as A.That, not obj.That.

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.

How to move nested class in superclass in java?

I need to refactor class extracting abstract superclass.
E.g.
UpperClass {
NestedClass {
UpperClass.this.someMethod();
}
}
Like:
AbstractUpperClass {
NestedClass {
?????.this.someMethod();
}
}
After I plan inherit AbstractUpperClass in 2 classes UpperClass1 and UpperClass2.
But I don't know how to refactor this inner class because it inovokes method of enclosing class. Does it possible?
Thanks.
The trick here is knowing how the inner class works. It's essentially just a "normal", static class, but whose constructor implicitly gets a reference to the enclosing class. So, this:
public class TopLevel {
public void go() {
new Inner().bar();
}
public void foo() { }
public class Inner {
public void bar() {
TopLevel.this.foo();
}
}
}
is equivalent to this:
public class TopLevel {
public void go() {
new Inner(this).bar(); // explicitly passing in "this"
}
public void foo() { }
public static class Inner {
private final TopLevel parent; // note that we have this new field
public Inner(TopLevel parent) { // note this new constructor
this.parent = parent;
}
public void bar() { // we use the explicit reference instead
parent.foo(); // of the implicit TopLevel.this
}
}
}
So, with all that said, the way to refactor your inner class to be a top-level class is to add an explicit field referencing the UpperClass instance, and passing this reference into the NestedClass constructor. In other words, be like that second code snippet instead of the first.

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