Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
Now Reading
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
The anonymous class in Java is a way to create an unnamed class that extends a superclass or implements an interface on the fly. They are often used for one-time implementations or event handlers. Anonymous classes are defined and instantiated in a single step, providing a concise and inline approach for certain scenarios. Learn more about anonymous classes in this tutorial.
In this tutorial, we'll explore how to use anonymous class in Java with examples. You will also learn how to extend a superclass or implement an interface, providing a concise and inline approach for certain programming scenarios.
Here is the syntax for using the anonymous class in Java:
SuperClass obj = new SuperClass() {
// Anonymous inner class body
// Implementations of methods or additional members
};
Let us break down the syntax:
public class upGradTutorials {
public static void main(String[] args) {
// Creating an instance of the class using anonymous inner class
MyClass myClass = new MyClass() {
@Override
public void displayMessage() {
System.out.println("Hello, I'm an anonymous inner class!");
}
};
// Calling the method on the anonymous inner class object
myClass.displayMessage();
}
}
// Class to be extended by anonymous inner class
class MyClass {
public void displayMessage() {
System.out.println("Hello, I'm the base class!");
}
}
This example has a base class MyClass with a method displayMessage(). We create an instance of this class using an anonymous inner class. The anonymous inner class is defined and instantiated inline without explicitly declaring a separate class.
We override the displayMessage() method inside the anonymous inner class and provide our custom implementation. When we call the displayMessage() method on the anonymous inner class object, it executes the overridden method, printing "Hello, I'm an anonymous inner class!" to the console.
When we compile the Java code containing an anonymous inner class, the compiler generates a separate class file for the anonymous inner class. The generated class file has a name that combines the outer class's name, a dollar symbol ($), and a number. The number represents the order of appearance of the anonymous inner class in the code.
For example, if we compile the above code, the compiler will generate a class file named upGradTutorial$1.class for the anonymous inner class.
public class upGradTutorials {
public static void main(String[] args) {
// Creating an instance of the interface using an anonymous inner class
MyInterface obj = new MyInterface() {
@Override
public void doSomething() {
System.out.println("Anonymous inner class implementation of doSomething method");
}
};
// Calling the method using the interface reference
obj.doSomething();
}
}
// Interface definition
interface MyInterface {
void doSomething();
}
Inside the main method, we create an instance of an anonymous inner class that implements the MyInterface interface. The anonymous inner class is defined using the new MyInterface() { ... } syntax.
We implement the doSomething() method within the anonymous inner class, which simply prints the message "Anonymous inner class implementation of doSomething method".
After creating the anonymous inner class instance, we assign it to a variable obj of type MyInterface. This allows us to reference the object and call methods defined in the interface.
Finally, we invoke the doSomething() method on the obj object, which calls the overridden doSomething() method within the anonymous inner class and prints the desired message to the console.
The Java compiler generates a class for the anonymous inner class behind the scenes, with a name similar to upGradTutorials$1. This internal class contains the implementation of the interface method. However, as a developer, we do not need to explicitly create this class, as the compiler automatically generates it.
The generated class is a subtype of the interface or superclass that the anonymous inner class implements or extends. In this case, the compiler generates a class file that implements the MyInterface interface.
The generated class has a synthetic name, meaning it is not explicitly named in the source code. It allows us to create an interface instance without explicitly defining a separate class that implements the interface. The anonymous inner class simplifies the code by providing a concise way to implement interfaces or extend classes on-the-fly without the need for a separate named class implementation.
Anonymous inner classes in Java can be classified into two types:
public class upGradTutorials {
public static void main(String[] args) {
// Creating an instance of the abstract class using an anonymous inner class
AbstractClass obj = new AbstractClass() {
@Override
public void display() {
System.out.println("Anonymous inner class implementation of display method");
}
@Override
public void additionalMethod() {
System.out.println("Additional method implementation in the anonymous inner class");
}
};
// Calling methods using the abstract class reference
obj.display();
obj.additionalMethod();
}
}
// Abstract class definition
abstract class AbstractClass {
public abstract void display();
public void additionalMethod() {
System.out.println("Default implementation of additionalMethod");
}
}
In this example, we define an anonymous inner class that extends the AbstractClass abstract class. The anonymous inner class provides implementations for the abstract display() method and another method, additionalMethod().
Inside the main method, we create an instance of the AbstractClass using the syntax new AbstractClass() { ... }. Within the anonymous inner class, we override the display() method and provide a custom implementation that prints a specific message. We also override the additionalMethod() and provide a custom implementation.
After creating the anonymous inner class instance, we assign it to a variable obj of type AbstractClass. This allows us to reference the object and call the overridden methods.
Finally, we invoke the display() and additionalMethod() methods on the obj object. Since the anonymous inner class extends the AbstractClass, the overridden implementations within the anonymous inner class are executed, printing the custom messages to the console.
public class upGradTutorials {
public static void main(String[] args) {
// Creating an instance of the interface using an anonymous inner class
MyInterface obj = new MyInterface() {
@Override
public void printMessage(String message) {
System.out.println("Anonymous inner class implementation: " + message);
}
@Override
public void additionalMethod() {
System.out.println("Additional method implementation in the anonymous inner class");
}
};
// Calling methods using the interface reference
obj.printMessage("Hello, World!");
obj.additionalMethod();
}
}
// Interface definition
interface MyInterface {
void printMessage(String message);
void additionalMethod();
}
This example defines an anonymous inner class that implements the MyInterface interface. The anonymous inner class provides implementations for the printMessage() method and another method, additionalMethod().
Inside the main method, we create an instance of the MyInterface using the syntax new MyInterface() { ... }. Within the anonymous inner class, we override the printMessage() method and provide a custom implementation that prints the message with additional text. We also override the additionalMethod() and provide a custom implementation.
After creating the anonymous inner class instance, we assign it to a variable obj of type MyInterface. This allows us to reference the object and call the overridden methods.
Finally, we invoke the printMessage() and additionalMethod() methods on the obj object. Since the anonymous inner class implements the MyInterface, the overridden implementations within the anonymous inner class are executed, printing the custom messages to the console.
Anonymous classes in Java provide several advantages:
Anonymous class in Java provides a powerful and convenient way to define and instantiate classes inline without separating class declarations. They offer advantages such as conciseness, localized implementations, improved code readability, access to local variables, customization, and flexibility.
Anonymous classes are beneficial for one-time implementations, event handling, and providing custom implementations for abstract classes or interfaces. You can write more concise, focused, and readable code in Java by leveraging anonymous classes. Sign up for a professional course at upGrad to hone your skills in various Java concepts.
Anonymous classes are defined and instantiated inline without a specific class name. Anonymous classes in Java are declared and instantiated simultaneously, allowing you to create a one-time-use class without explicitly defining it.
Anonymous classes can implement interfaces in Java by providing the necessary implementation for the interface methods within the body of the anonymous class declaration.
Lambda expressions are a concise way to represent anonymous functions, offering a more streamlined syntax than anonymous classes for functional programming tasks.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...