INNer classes & Packages
Inner Classes:
A class that
is defined in another class is called as an inner class.
There are
four types of inner classes:
1) Member class 2) Static member class
3) Local class 4) Anonymous class
1)
Member class:
A class that
is defined as member of another class is called as member class.
Example:
class A
{
class B
{
void show()
{
System.out.println(“Welcome”);
}
}
}
class Demo
{
public static void main(String
args[])
{
A a=new A();
A.B b=a.new B();
b.show();
}
}
2)
Static Member Class:
A class that
is defined as a static member of another class is called as static member
class.
Example:
class A
{
static class B
{
void show()
{
System.out.println(“Welcome”);
}
}
}
class Demo
{
public static void main(String
args[])
{
A.B b=new A.B();
b.show();
}
}
3)
Local Class:
A class that
is defined inside a method is called as local class.
Example:
class Demo
{
public static void main(String
args[])
{
class Test
{
void show()
{
System.out.println(“Welcome”);
}
}
Test t=new Test();
t.show();
}
}
4)
Anonymous Class:
It is a one
type of local class which has no name. It is always sub class of a class or interface.
Example:
interface
Test
{
void show();
}
class Demo
{
public static void main(String
args[])
{
Test t=new Test()
{
public void
show()
{
System.out.println(“Welcome”);
}
};
t.show();
}
}
Outer classes cannot be private and cannot be protected.
Member class & Static member class can have all access modifiers.
Access modifiers cannot be applied
to local class and anonymous class.
Packages:
A package is
a collection of sub packages, classes & interfaces.
Example:
package
pack1;
public class
A
{
public void add(int a, int b)
{
System.out.println(a+b);
}
}
C:\src>javac
–d C:\classes A.java
package
pack1.pack11;
public class
B
{
public void max(int a, int b)
{
if(a>b)
System.out.println(a);
else
System.out.println(b);
}
}
C:\src>javac
–d C:\classes B.java
package
pack2;
public class
C
{
public void cube(int a)
{
System.out.println(a*a*a);
}
}
C:\src>javac
–d C:\classes C.java
package
test;
import
pack1.*;
import
pack1.pack11.*;
import
pack2.*;
class Main
{
public static void main(String
args[])
{
A a=new A();
a.add(83, 45);
B b=new B();
b.max(87, 45);
C c=new C();
c.cube(8);
}
}
C:\src>set classpath=”%classpath%”.;C:\classes;
C:\src>javac –d C:\ Main.java
C:\>java test.Main
No comments:
Post a Comment