Anonymous Inner Class
--> A class without name, it is useful when we have to add some extra features from using superclass, For this you can make overriding, but what is the need of overriding if you can implement this without extends superclass, see example
package basic;
class Class_Super {
void methodfirst() {
System.out.println("hi nilesh from method first");
}
void methodSecond() {
System.out.println("hello neeraj from method second ");
}
}
public class Anonymous_InnerClass {
public static void main(String args[]) {
Class_Super obj = new Class_Super() {
@Override
void methodfirst() {
System.out.println("bye from Anonymous Inner Class");
}
};
obj.methodfirst();
}
}
class Class_Super {
void methodfirst() {
System.out.println("hi nilesh from method first");
}
void methodSecond() {
System.out.println("hello neeraj from method second ");
}
}
public class Anonymous_InnerClass {
public static void main(String args[]) {
Class_Super obj = new Class_Super() {
@Override
void methodfirst() {
System.out.println("bye from Anonymous Inner Class");
}
};
obj.methodfirst();
}
}
output--
bye from Anonymous Inner Class
----> Here see, we take superclass reference varible and create one object, means a class without name, and then override same method and add extra implementation.
Note-But there is some disadvantages of it, if you have to create more than one object then you will have to make two Anonymous classes, means for one object there must be only one Anonymous class.
if any query please let me know
Thanks
Keep Learning.... :)
No comments:
Post a Comment