public class InnerEx7 {
    
    public static void main(String[] args) {
        Foo foo=new Foo();
        Foo foo2=foo.stam(55);
        foo2.print();
    }
}

class Foo{
    String word="bye";
    void print(){} // what does this fucntion do. why do i need it if it is empty
    public Foo stam(final int x){
        final int y=10;

        class Inner extends Foo{ // why do i need to use inheritance here?
            public void SayHello() {
                System.out.println("Hello");
            }
            @Override
            void print() {
                System.out.println(y*x);
                System.out.println("Print "+word );
            }
        }
        Inner inner=new Inner();
        inner.SayHello();
        return inner;
    }

}

Recommended Answers

All 28 Replies

why do i need to use inheritance here?

Why do you think you need to extend Foo there?

What happens when you try to compile it without the extension?

i have no idea. i got the code from my teacher. but i dont understand why do you need to use inheritance.

i know inner loops can work without inheritance. but still why to use inheritance?

What happens when you try to compile it without the extension?

i didnt try. but i think nothing is happening. why should something happen?

Lack of curiosity?
You're the one that asked the question: // why do i need to use inheritance here?

i was asking to know , when will i use inheritance in inner loops. is it useful?

I don't know what inheritance has to do with inner loops.

me too..lol

what does this fucntion do. why do i need it if it is empty

You may insert some code into the method void print(){...}. If there is no such a method,
the line 23 @Override
should be deleted.

why do i need to use inheritance here?

In the class InnerEx7 foo2 (the instance of the class Inner) is created as an instance of Foo's subclass. If the class Inner does not inherit Foo, in the class InnerEx7 there is no way to get an instance of Inner since the class Inner is not recognined outside of the class Foo.

the line 23 @Override
should be deleted.

Why? It's perfectly valid and very useful.

In the class InnerEx7 foo2 (the instance of the class Inner) is created as an instance of Foo's subclass. If the class Inner does not inherit Foo, in the class InnerEx7 there is no way to get an instance of Inner since the class Inner is not recognined outside of the class Foo.

This is very confusing, but appears to be wrong. An instance of an inner class that does not inherit from the containing class can be recognised anywhere as long as you have a reference to it. That's what happens when you use an anonymous inner class as a Listener for Swing events etc. However, in an example like the OP's one, I guess it has to extend some class or interface that is accessible outside the containing class - it just doesn't need to be the containing class.

It's (the term override) perfectly valid

If the void print() method does not exist in the class Foo one can not override it in the sub-class Inner anymore. In other word, in the sub-class the void print() method is newly created, if its super class has no such a method. Therefore, if the void print() method is removed in the the super class Foo the term @Override should be deleted, implying the void print() method is newly created.

Yes, that's true, but there IS such a method in Foo, and nobody is suggesting that it should be removed, so what's your point?

public class AnonyEx3 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new Stam().foo(100,25));
    }
}
class Stam
{
    public int  foo(int d,final int y){
        int x= new Person(d){
            public int getDoubleAge() {
                return age*y;
            }
        }.getDoubleAge(); // why another method is attacked to it? why to create 2 methods attached?
        return x;
    }
}

class Person{
    
    String name;
    int age;
    public Person(int age) {
        this.age = age;
    }
    
}
/*
class ... extends Person{
    public Person(int age) {
        super(age)
    }
    public int getDoubleAge() {
                return age*age;
            }
}
*/

is this anonymous class?

No. An anonymous class has no name (hence "anonymous"). It is declared, defined and used in one place, and has no need of a name. They are typically used to create listener objects for AWT events, or new Threads, as in:

new Thread(new Runnable() {
         @Override
         public void run() {
            // do a load of stuff;
         }
      }).start();

This code declares a class that implements the Runnable interface

Runnable() {...}

provides the method that is required by the Runnable interface

@Override
         public void run() {
            // do a load of stuff;
         }

creates a new instance of it

new Runnable ...

and passes that to the constructor for a new Thread

new Thread(new Runnable...

and starts the Thread running

.start();

It looks a bit odd at first, but it's a very common construct that rapidly becomes an automatic thing to code (and most IDEs will generate one for you anyway).

I have no idea what your Stan class is supposed to do, or why it's constructed that way, sorry.

james. can you explain me the syntax. how does this syntax called?

#
int x= new Person(d){
#
public int getDoubleAge() {
#
return age*y;
#
}
#
}.getDoubleAge(); // why another method is attacked to it? why to create 2 methods attached?

Sorry - no time now. I was wrong - that IS an anonynmous inner calss. I;ll post more in th emorning.

commented: thanks for helping +0

back online now. Sorry about the error in my previous post. It was only the first word that was wrong. Replace it with Yes and the post is OK.

The new Person(d)... code is an anonymous inner class.
Its syntax works just like the example I described line-by-line yesterday, so have another look at that.
About your latest code specifically: you are still confusing defining/creating a method with calling/using a method. Your code fragment defines a method getDoubleAge within the anonymous class definition, then on line 10 it calls that same method. If you compare it with the example I gave yesterday you can work out that your code:
defines an anonymous inner class that is a subclass of Person
defines a method getDoubleAge in that class (this probably overrides a method of the same name in Person)
creates a new instance of the anonymous class
calls the getDoubleAge method on that instance.

hi i produced a video explaining how the code that i posted works. the quality is bad. i tried to improve it , but i cant do anything about it.. if you could copy and paste my code into a notepad and watch the vid.

i want to see if i lack in understanding anywhere in the code..

http://www.youtube.com/watch?v=eEclvzRTiqI


tong made a really good point, he said that that kind of inheritance improves visibility. is it true. can you expand on it a bit?

I tried to watch the vid but (on my laptop) the sound was too faint and muffled to be able to hear what you said. Anyway, I don't really have time for that kind of one-on-one mentoring.

Please make comments on my remarks on the following example I made of anonymous inner class.
The first anonymous inner class inheritants the abstract adapter class MouseAdapter while the second anonymous inner class extends the abstract adapter class WindowAdapter. Be noticed that not only the two inner classes have no names but also the two instances created by the inner classes have no references.
The advantage of this way to write code is simple and concise. For example, when you have to implement only one method of a interface, e.g. the mouseClicked() of the MouseListener,the rest methods of the corresponding interface will not bother you. If you implement an interface you have to implement all its methods.
The disadvantage is there are no references(name, status) to follow anywhere. Thus in rest code (e.g. outside of the containing class) there is no way to refer to them.

import javax.swing.*;
import java.awt.event.*;
public class InnerEx8   extends JFrame{    
 int x,y;
 public InnerEx8(){
 	x=0;
 	y=0;
 	// register the mouseListener 
 	addMouseListener (new MouseAdapter(){// the first anonymous inner class
 		public void mouseClicked(MouseEvent e) { //implement the mouseClicked method 
 		System.out.println("x= " + e.getX() + ", y= " + e.getY()); /* On DOS window print the coordinate of the location clicked */
 		}
 	});
 	setSize(400,400);
 	setVisible(true);
    }
    public static void main(String[] args) {
        InnerEx8 ie= new InnerEx8();
        /* register listener for windowClosing event */
        ie.addWindowListener( new WindowAdapter(){ /* the second anonymous inner class for windowClosing event */
     	public void windowClosing(WindowEvent event){ /* implement the windowClosing method */
   		System.exit(0); // terminate appliction when user closes window
       	}
        }); 
    }
}

Please make comments on my remarks on the following example I made of anonymous inner class.
The first anonymous inner class inheritants the abstract adapter class MouseAdapter while the second anonymous inner class extends the abstract adapter class WindowAdapter. Be noticed that not only the two inner classes have no names but also the two instances created by the inner classes have no references.
The advantage of this way to write code is simple and concise. For example, when you have to implement only one method of a interface, e.g. the mouseClicked() of the MouseListener,the rest methods of the corresponding interface will not bother you. If you implement an interface you have to implement all its methods.
The disadvantage is there are no references(name, status) to follow anywhere. Thus in rest code (e.g. outside of the containing class) there is no way to refer to them.

import javax.swing.*;
import java.awt.event.*;
public class InnerEx8   extends JFrame{    
 int x,y;
 public InnerEx8(){
 	x=0;
 	y=0;
 	// register the mouseListener 
 	addMouseListener (new MouseAdapter(){// the first anonymous inner class
 		public void mouseClicked(MouseEvent e) { //implement the mouseClicked method 
 		System.out.println("x= " + e.getX() + ", y= " + e.getY()); /* On DOS window print the coordinate of the location clicked */
 		}
 	});
 	setSize(400,400);
 	setVisible(true);
    }
    public static void main(String[] args) {
        InnerEx8 ie= new InnerEx8();
        /* register listener for windowClosing event */
        ie.addWindowListener( new WindowAdapter(){ /* the second anonymous inner class for windowClosing event */
     	public void windowClosing(WindowEvent event){ /* implement the windowClosing method */
   		System.exit(0); // terminate appliction when user closes window
       	}
        }); 
    }
}

tong what is this annotation when you have .method() after the inner class.. what does it mean?

public class AnonyEx3 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new Stam().foo(100,25));
    }
}
class Stam
{
    public int  foo(int d,final int y){
        int x= new Person(d){
            public int getDoubleAge() {
                return age*y;
            }
        }.getDoubleAge();
        return x;
    }
}

class Person{
    
    String name;
    int age;
    public Person(int age) {
        this.age = age;
    }
    
}
/*
class ... extends Person{
    public Person(int age) {
        super(age)
    }
    public int getDoubleAge() {
                return age*age;
            }
}
*/
class Stam  // the containing class Stam has an anonymous inner class
{
    public int  foo(int d,final int y){  
        int x= new Person(d){    // this anonymous inner class extends the class Person.
            public int getDoubleAge() { //in this inner sub-class a method public int getDoubleAge() is added or overridden if it does pre-exist in the class Person.
                return age*y;
            }
        }.getDoubleAge(); // the handle for the method getDoubleAge() is the anonymous instance of the anonymous inner class
        return x;
    }
}

A couple of quick points.
1. Don't confuse extending a class with implementing an interface. They are different.

when you have to implement only one method of a interface, e.g. the mouseClicked() of the MouseListener,the rest methods of the corresponding interface will not bother you. If you implement an interface you have to implement all its methods.

So in this quote the first sentence would be right if it referred to extending a class.

The disadvantage is there are no references(name, status) to follow anywhere. Thus in rest code (e.g. outside of the containing class) there is no way to refer to them.

That's not right. If you use the new anonymous instance as a parameter to a call, as in
myButton.addActionListener(new ActionListener() {...
then,, in this case, myButton now has a reference to the instance which it can use, or pass further on to anywhere else in the program.

JamesCherrill, I don't understand the second point you made.
How can we reuse the instance the myButton does have? For example, if I want to add the same addActionListener as the myButton to another button, e.g. myButton1, I have to rewrite the definition of the anonymous inner class because I have no way to refer to it. Is there a way to refer to that previous anonymous inner class?

Good question. Short answer: you can't*.
If you want to use the same Listener class for multiple buttons then you should create a normal named (inner) class - the anonymous version only works well for one-time single-use cases.
* Well, there's always a way... Because the first button has a ref to that instance you can use getActionListeners() on the first button to get a reference to the anonymous listener, then add that to another button, but that's a bit of a hack.

Thank you very much indeed James. Thank you for your comments. I will try the method getActionListeners() to have a taste in getting a reference to an instance of an anonymous inner class . I am also noticed that the return data type of the method is an array: public ActionListener[] getActionListeners().
I hope it will work fine.

Should be fine. If youy only add 1 listener it should be in [0] of the array.
ps: Although you don't give the class a name, the compiler generates one by adding $1 (etc) the the outer class name. You will see these in the generated .class files.

class Stam  // the containing class Stam has an anonymous inner class
{
    public int  foo(int d,final int y){  
        int x= new Person(d){    // this anonymous inner class extends the class Person.
            public int getDoubleAge() { //in this inner sub-class a method public int getDoubleAge() is added or overridden if it does pre-exist in the class Person.
                return age*y;
            }
        }.getDoubleAge(); // the handle for the method getDoubleAge() is the anonymous instance of the anonymous inner class
        return x;
    }
}

why is it useful to inbox the constructor holding an anonymous class..
why not simply call for a method and using a reference.

person.getDoubleAge.

does the anonymous class lives ones?

so i X receives what the methods .getDoubleAge() gives it//.. right?
all what is inside the anonymous class is an extension

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.