Types of class
- Member class
- Inner class
- Nested class
- Abstract class
- Anonymous class
- Interface
Member Class:
Inner class
Non-static nested class is a class within another class, where the class has access to members of the enclosing class (outer class). It is commonly known as Inner class.Since, inner class exists within the outer class where as the outer class must be instantiated before instantiating the inner class.
class OuterClass {
// ...
class InnerClass {
// ...
}
}
Syntax: Outerclass Obj = new Outerclass(); // Outerclass instatiation
Outerclass.Innerclass InnerObj = Obj.new Innerclass(); //Innerclass instatiation with outer class object
For Example:
class Dog{
void sound(){
System.out.println("Animal barking");
}
static class Doberman{
void bark(){
System.out.println("Doberman barking");
}
}
}
class Animal{
public static void main(String arg[]){
System.out.println("Animal sound");
Dog d=new Dog();
d.sound();
Dog.Doberman db= d.new Doberman();
db.bark();
}
}
Output:
Animal sound
Animal barking
Doberman barking
Nested Inner class
class OuterClass {
// ...
static class NestedClass {
// ...
}
}
Syntax: Outerclass.Innerclass InnerObj = new Outerclass.Innerclass(); /Innerclass instatiation without outer class objectFor Example:
class Dog{
void sound(){
System.out.println("Animal barking");
}
static class Doberman{
void bark(){
System.out.println("Doberman barking");
}
}
}
class Animal{
public static void main(String arg[]){
System.out.println("Animal sound");
Dog d=new Dog();
d.sound();
Dog.Doberman db=new Dog.Doberman();
db.bark();
}
}
Output:
Animal sound
Animal barking
Doberman barking
Anonymous class:
class
No comments:
Post a Comment