I have an inner class which is present inside a method and this class has a method.
I want to use the method which is present in my inner class method outside of my current package.
Can you suggest me how to use it?
package com.a3.local;
public class OuterClass
{
public void outerMethod()
{
class InnerClazz
{
public void wakeUp()
{
System.out.println("Good Morning");
}
}
}
}
As others explained you can access to your method local defined inner-class (using an interface => see other answers).
Anyway I don't think this is the purpose of defining a method-local class.
We can access the inner class method outside the package.
We need to create an instance of the Outerclass and then create an instance of the inner class using the outer class. After that we can call it.
code from tutorial : http://www.oursland.net/tutorials/java/innerclasses/
public class InnerClassTest {
public void foo() {
System.out.println("Outer class");
}
public class ReallyInner {
public void foo() {
System.out.println("Inner class");
}
public void test() {
this.foo();
InnerClassTest.this.foo();
}
}
public static void main(String[] args) {
InnerClassTest o = new InnerClassTest();
InnerClassTest.ReallyInner i = o.new ReallyInner();
i.test();
As far as I understood the code looks like:
class Outer
{
public void someMethod()
{
class Inner{
public void methodThatShouldBeVisibleOutside() {}
}
}
}
The only way is to have the Inner class implements a publicly visible interface 'InnerInterface' and return an instance of the Inner class and invoke the methodThatShouldBeVisibleOutside:
public InnerInterface someMethod()
{
class Inner implements InnerInterface()
{
#Override
public void methodThatShouldBeVisibleOutside() {}
}
return new Inner();
}
Then
new Outer().someMethod().methodThatShouldBeVisibleOutside();
If the inner class is defined in a method, calling its methods (without reflection) requires that:
The class implement an interface accessible to the caller.
An instance of the class is accessible to the caller.
There's an example at http://java.sun.com/new2java/divelog/part5/page5.jsp .
Your class has to be public and have a name and be defined in the class body, not inside a method for you to be able to use it in other packages directly, instead of just using it by its base type or one of its interface types.
If you have a class mypackage.Outer that defines an inner class Inner, you can refer to the class using the name mypackage.Outer.Inner and import that as normal to shorten the name.
If it's static, you can create it using the new mypackage.Outer.Inner(...).
If it's not static, you have to use a different syntax to create them : myOuterInstance.new mypackage.Outer.Inner(...).
First of all, your inner class must have a public visibility and be static.
Then, there's two possibilities :
You want to call a static method of your inner class
You want to call a method on an instance of your inner class
In the first case, if the visibility are setted right, you can simply do :
OuterClass.InnerClass.myStaticMethod()
In the seconde class, you must provide a way to retrieve an instance of the inner class and simply invoke the method on the instance as you'll do with any other method.
It is also possible to call a method on a non static inner class, but this is way more complicated. A code snippet will really helps here ;)
Hope this helps.
Related
Code description and ouput
In the following code. We have a class TestInners, one inner class A, one method local inner class A and one outer class A.
When we instantiate an object as in new A().m(); the ouput is
middle.
In order for the program to output inner we must instantiate the object after the method local inner class A in the gomethod.
If we comment the inner class the program will output outer.
Question
In the code as it is. Why did it output middle? Is there a preference for the inner classes first? then the outer classes? I got confused.
Source code
class A { void m() { System.out.println("outer"); } }
public class TestInners {
public static void main(String[] args) {
new TestInners().go();
}
void go() {
new A().m();
class A { void m() { System.out.println("inner"); } }
}
class A { void m() { System.out.println("middle"); } }
}
Yes, if you shadow symbols with more local definitions, the more local one is chosen. This most frequently happens with method parameters vs instance fields, leading to the famous this.name = name idiom.
In your case, you can get to the outer class by using a fully qualified class name.
But don't name classes like that. Too much confusion for no reason.
If I have the following class
public class Foo {
public void bar(){
fooBar();
}
private void fooBar(){
System.out.println("text...");
}
}
instead I can also do something like
public class Foo {
public void bar() {
new inner().fooBar();
}
private class inner {
private void fooBar() {
System.out.println(" text ...");
}
}
}
when should I use inner classes instead of private method? If the functionality is specific to the class Foo then it make sense to use an inner class but the same can also be achieve d through private method which can only be accessed within the class itself.
For your example, you don't need an inner class. Your first solution is simple, easy-to-read, and sufficient.
An inner class is useful when:
You need to implement an interface, but don't want the outer class to implement it.
There can be more than one instance of the class.
There can be more than one type of the inner class.
EDIT: Examples of each, by request
An interface might be implemented by an inner class to implement the Iterator pattern, or a Runnable, ...
Multiple instances of an inner class could be necessary to implement an iterator, or a special key type to an internal map, ...
Multiple types of inner classes might be necessary for the Strategy pattern, ...
I have made these 2 classes to make use of the concept of anonymous inner class.
Class 1 has a static inner class. And class 2 uses it. But i cant understand how to call the method of the inner class. Please help me out.
Class 1
public class outerclass {
outerclass() {
System.out.println("Constructor of new class");
}
public void showthis(String str) {
System.out.println(str);
}
static class insideclass {
insideclass() {
System.out.println("This is inside class constructor");
}
public void nowshowthis(String str) {
System.out.println(str);
}
}
}
Class 2
public class helloworld {
public static void main(String args[]) {
//this is an object of the outer class
outerclass example=new outerclass();
//How do i make an anonymous inner class and call the method "nowshowthis()"
}
}
An anonymous inner class is one that is created AND defined within the body of another class's method. In essence, you are creating a concrete class on the fly from an abstract definition. What you have so far with your InnerClass class is actually just a regular inner class, meaning non-anonymous.
If you want to experiment with anonymous inner classes, the simplest way I can think of is to change your InnerClass to an interface, like so:
public interface InnerClass{
public void doSomething();
}
So at the moment, InnerClass does squat; it has no meaning until it is defined. Next, you'll want to change how OuterClass works. Change your showThis() function like so:
public showThis(InnerClass innerObj){
innerObj.doSomething();
}
Now we have your outer class asking the inner class instance to do something, but we still have not defined what it is we want it to do. This is where the magic happens - in your main method, you will define what the inner class instance actually looks like:
public static void main (String[] args){
OuterClass outer = new OuterClass();
// This is the key part: Here you are creating a new instance of inner class
// AND defining its body. If you are using Eclipse, and only write the
// new InnerClass() part, you'll notice that the IDE complains that you need
// to implement the doSomething() method, which you will do as though you
// were creating a plain 'ol class definition
outer.showThis(new InnerClass(){
public void doSomething(){
System.out.println("This is the inner anonymous class speaking!");
}
});
}
In practice, I've not used anonymous inner classes too much, however they are useful to know about. I have used them most often when I am doing GUI programming, to define listeners for GUI control events, such as a button click.
Also, as other people have mentioned, keep in mind that the Java standard has the first letter of the class name a capital letter, which I have done here. You'll want to follow that standard as it makes it far easier for other people to read your code, and at a glance you can very easily tell when you're looking at a class, and when you're looking at an object.
Anyways, hope that helps.
Let me just get out of my immediate issue! If your inner class in non-static this is how to instanciate it: (assuming example to be an object of type outerclass)
example.new insideclass().nowshowthis("my String")
For static public inner class, you don't even need an instance of outer class. Just do this (much like accessing public static variable)
new outerclass.insideclass().nowshowthis("my String")
have you tried this?
What's the deal? In your case, you are not really dealing with Anonymous inner class. It's actually just a plain vanilla inner class. (I can't rationalize why would you do that.)
So what's an anonymous class, and where we use it? An anonymous class is like an instance of class for one time use. One of the examples comes to surface when you implement some interface... but you do not need to use it other wise. For example you want to attach a handler to a button. You can do it much like in this fashion (hypothetical example)
MyButtonInterface obj= new MyButtonInterface(){
#Override
onClick(Model obj){
//save model in DB
}
}
UI.add(obj, "specificId");
you see?
insideclass is an non-static class so it must be accessed via an instance of the outer class as follows:
new outerclass().new insideclass().nowshowthis();
That is not an anonymous inner class. Here is an example of an anonymous inner class:
class InnerClassDemo {
public static void main(String[] args) {
ActionListener a = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
};
// now a is the only instance of an anonymous inner class implementing the ActionListener interface
}
}
You can of course also do this with your own interface or class:
class InnerClassDemo {
public class InsideClass {
InsideClass() {
System.out.println("This is inside class constructor");
}
public void nowshowthis(String str) {
System.out.println(str);
}
}
public static void main(String[] args) {
InsideClass anonym = new InsideClass() {
#Override
public void nowshowthis(String str) {
System.out.println("anonymous inner class override: "+str);
}
}
InsideClass normalInstance = new InsideClass();
anonym.noshowthis("test");
normalInstance.noshowthis("test");
}
}
Your output will be
anonymous inner class override: test
test
So anonym is an instance of an anonymous inner class implementation of InsideClass while normalInstance is just a normal instance of your class InsideClass.
public class HelloWorld {
public static void main(String args[])
{
outerclass.insideclass example= new outerclass.insideclass();
example.nowshowthis("Hello");
}
}
Or, make the nowshowthis method static and it can be called like so:
outerclass.insideclass.nowshowthis("Howdy. This method is static.");
I have a Java problem with nested classes.
My first class structure looked like this:
public class TopClass {
public void mainMethod() {
// uses the different "method" methods from
// NestedClass-implementing nested classes
}
private interface NestedClass {
public void method();
}
private class NestedClass1 {
public void method() {
}
}
private class NestedClass2 {
public void method(){
}
}
}
But now I want these method() methods to be static because they should be principally.
I cannot make them static without having them in a static class, but that's no problem, I made the classes static, they should be anyway.
It looks like this right now:
public class TopClass {
public void mainMethod() {
// uses the different "method" methods from
// NestedClass-implementing nested classes
}
private static interface NestedClass {
public void method();
}
private static class NestedClass1 {
public static void method() {
}
}
private static class NestedClass2 {
public static void method(){
}
}
}
But then the trouble begins. A static method does not inherit correctly from a non-static interface method, as I get this message This static method cannot hide the instance method from TopClass.NestedClass in Eclipse.
When I make the interface method static, it gives me this error: Illegal modifier for the interface method method; only public & abstract are permitted
So I thought of an abstract class, and tried this:
public class TopClass {
public void mainMethod() {
// uses the different "method" methods from
// NestedClass-implementing nested classes
}
private static abstract class NestedClass {
public static abstract void method();
}
private static class NestedClass1 {
public static void method() {
}
}
private static class NestedClass2 {
public static void method(){
}
}
}
But again, seemingly abstract methods cannot be declared static: The abstract method method in type NestedClass can only set a visibility modifier, one of public or protected.
Leaving the static away (in the abstract class method), errors this on the method methods in the NestedClass1 & 2: This static method cannot hide the instance method from TopClass.NestedClass.
Isn't there any way to declare some kind of superstructure for covering static methods?
EDIT:
The problem I actually try to solve it the lack of possibility of Java for storing references to methods. So instead I have those classes everyone with just one method, but to store them in a List f.e. they must be able to be "caught" by a superstructure.
I got the hint to try anonymous classes or enums, gonna try that now.
Interfaces and statics don't go together. At all. There is no Java support for creating / imposing patterns on static methods.
A static method declaration must always be followed by a definition. It cannot be implemented by subclasses.
I think you're just not approaching your problem right. Try a different approach!
Make NestedClass an interface NestedInterface and store your different implementations as anonymous classes implementing this interface:
public static final NestedInterface firstNested = new NestedInterface() {
#Override
public void method() {
// ...
}
};
Make NestedClass an enumeration NestedEnum and store your different implementations as enumeration values implementing an abstract method from the enumeration. This only works if you have a fixed number of implementations you which to choose from and you do not want to accept NestedClass implementations from outside sources.
public enum NestedEnum {
FIRST {
#Override
public void method() {
// ...
}
};
public abstract void method();
}
EDIT: In reply to your comment:
The classes itself are static as well..
static in the context of a nested class means that this class can be instantiated without an instance of the containing class.
A regular nested class such as in your first example can be instantiated through TopClass.this.new NestedClass1(). Normally you'd simply write new NestedClass1() from within the constructor or an instance method of TopClass, but in this verbose form you can clearly see the dependence on TopClass.this. This can also be seen from any method of NestedClass1, as you have access to the containing class with TopClass.this.
A static nested class such as in your second example can be instantiated through new TopClass.NestedClass1(). Once again, you could just write new NestedClass1() but the verbose form clearly shows that the construction only depends on TopClass and is not associated with an instance of TopClass. You could even create an instance from an outside class using the same snippet new TopClass.NestedClass1() without ever creating a TopClass instance.
I suggest you take a look at this question on inner classes and static nested classes.
The fact the your interface/abstract class is nested is irrelevant to the problem.
You just can't. There is no way in Java to enforce some class to implement static methods. Just cry and surrender and use instance methods.
static abstract is a contradiction. Static methods are not like other languages' class methods. When you make a static method it goes on a single class, it doesn't get inherited by or have its implementation deferred to subclasses.
You don't explain why you want these methods to be static. If you want these methods to be defined by subclasses then they shouldn't be.
i am trying to pass method local inner class object as an argument to some other function either in the scope of outside class or out of that class
public class MethodClass {
public void p(){
class h{
public void h1(){
System.out.print("Java Inner class");
}
}
h h2=new h();
}
}
here h2 i want to pass to any other function in the same class MethodClass or out of that class. can any one give me the procedure to pass the argument in that way?
If another method needs to know about the class, then you shouldn't declare it within a method, basically. Make it a nested class within the class itself, or even a top-level class.
I can't say I've ever used method-local class declarations.