Monday, July 19, 2010

Anonymous and Inner Class - example

an example of a simple anonymous class


public class MainClass {
public static void main(String[] args) {
Ball b = new Ball() {
public void hit() {
System.out.println("You hit it!");
}
};
b.hit();
}

interface Ball {
void hit();
}
}

and

-------------------------------------------------------
package com;

public class AnuClass {

/**
* @param args
*/


public static void myanmethod(){

Ball b = new Ball(){
public void hit() {
System.out.println("You hit it!");
}
};
b.hit();
}

interface Ball {
void hit();
}

public static void main(String[] args) {
AnuClass.myanmethod();




}
}
-------------------------------------------------------


Access inner class from outside


public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
outer.new Inner().hello();
}
}
class Outer {
public class Inner {
public void hello(){
System.out.println("Hello from Inner()");
}
}
}


------------------------------------------------------

Access inner class from outside


public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
outer.new Inner().hello();
}
}
class Outer {
public class Inner {
public void hello(){
System.out.println("Hello from Inner()");
}
}
}


--------------------------------------------------------

package com;


public class InOutClass {

/**
* @param args
*/
public static void main(String[] args) {
Outer outer = new Outer();
outer.new Inner().hello();

new Thread(new Thread(){
int i=0;
public void run() {
try {
while (i<10) {
sleep(1000); System.out.print("1");
i++;
}
}
catch(InterruptedException ex) {}
}
}).start();

// second option

Thread t = new Thread(new Thread(){
public void run() {
int i=0;
try {
while (i<10) {
sleep(1000); System.out.print("2");
i++;
}
}
catch(InterruptedException ex) {}
}
});
t.start();

new Thread(new Runnable() {
public void run() {
int i=0;
while (i<10) { //sleep(1000); //sleep is not a method of Runnable Interface,its in Thread class
System.out.print("3");
}
}
}).start();

}


}

class Outer {
public class Inner {
public void hello(){
System.out.println("Hello from Inner()");
}
}
}

No comments: