Posts

Showing posts from July, 2012

Example for Outer class reference

/*
 * This is a real time example for out class reference
 *
 */
package tcase;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author visruth cv
 */
public class Outer extends JFrame {

    private String outerClassField = "some value1";

    public Outer() {
        super("title of the frame");
        setSize(600, 600);
        setLayout(new FlowLayout());
        JButton b = new JButton("Ok");
        b.addActionListener(new ActionListener() {
            private String outerClassField = "some value2";
            public void actionPerformed(ActionEvent e) {
                System.out.println(Outer.this.outerClassField); //line 29
                System.out.println(outerClassField); //line 30
            }
        });
        add(b);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Outer();
    }
}
The line no.29 gives…

Why is Class.this (ClassName.this) used?

//What is Class.this

package tcase;

/**
 *
 * @author visruth cv
 *
 */
public class First {

    final String visru;
    final Second second;

    First(String visru) {
        this.visru = visru;
        this.second = new Second(visru + "-second");
    }

    class Second {

        final String visru;
        final Third third;

        Second(String visru) {
            this.visru = visru;
            this.third = new Third(visru + "-third");
        }

        class Third {

            final String visru;
            final Fourth fourth;

            Third(String visru) {
                this.visru = visru;
                this.fourth = new Fourth(visru + "-fourth");
            }

            class Fourth {

                final String visru;

                Fourth(String visru) {
                    this.visru = visru;
                }

                void toPrint() {
                    System.out.println("By Current Obect: " + this.visru);
 …