Enums
An enum is a special "class" that represents a group of constants (unchangeable variables,
like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate the
constants with a comma. Note that they should be in uppercase letters:
Example
enum Level {
LOW,
MEDIUM,
HIGH
}
You can access enum constants with the dot syntax:
Level myVar = [Link];
Enum is short for "enumerations", which means "specifically listed".
Enum inside a Class
You can also have an enum inside a class:
Example
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = [Link];
[Link](myVar);
}
}
The output will be:
MEDIUM
Enum in a Switch Statement
Enums are often used in switch statements to check for corresponding values:
Example
enum Level {
LOW,
MEDIUM,
HIGH
}
public class Main {
public static void main(String[] args) {
Level myVar = [Link];
switch(myVar) {
case LOW:
[Link]("Low level");
break;
case MEDIUM:
[Link]("Medium level");
break;
case HIGH:
[Link]("High level");
break;
}
}
}
The output will be:
Medium level
Loop Through an Enum
The enum type has a values() method, which returns an array of all enum constants. This
method is useful when you want to loop through the constants of an enum:
Example
for (Level myVar : [Link]()) {
[Link](myVar);
}
The output will be:
LOW
MEDIUM
HIGH
Difference between Enums and Classes
An enum can, just like a class, have attributes and methods. The only difference is that enum
constants are public, static and final (unchangeable - cannot be overridden).
An enum cannot be used to create objects, and it cannot extend other classes (but it can
implement interfaces).
Why And When To Use Enums?
Use enums when you have values that you know aren't going to change, like month days,
days, colors, deck of cards, etc.
Java Inner Classes
Java Inner Classes
In Java, it is also possible to nest classes (a class within a class). The purpose of nested
classes is to group classes that belong together, which makes your code more readable and
maintainable.
To access the inner class, create an object of the outer class, and then create an object of the
inner class:
Example
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
}
// Outputs 15 (5 + 10)
Private Inner Class
Unlike a "regular" class, an inner class can be private or protected. If you don't want
outside objects to access the inner class, declare the class as private:
Example
class OuterClass {
int x = 10;
private class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass(); //won’t work
[Link](myInner.y + myOuter.x);
}
}
If you try to access a private inner class from an outside class, an error occurs:
[Link]: error: [Link] has private access in OuterClass
[Link] myInner = [Link] InnerClass();
^
Static Inner Class
An inner class can also be static, which means that you can access it without creating an
object of the outer class:
Example
class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
[Link] myInner = new [Link]();
[Link](myInner.y);
}
}
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access to
members of the outer class.
Access Outer Class From Inner Class
One advantage of inner classes, is that they can access attributes and methods of the outer
class:
Example
class OuterClass {
int x = 10;
class InnerClass{
public int myInnerMethod() {
return x;
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link]([Link]());
}
}
// Outputs 10
Shadowing
<see slides>
Local vs anonymous inner classes
Anonymous Inner Class in Java | Example, Use
An anonymous inner class in Java is an inner class which is declared without any class
name at all.
In other words, a nameless inner class is called anonymous inner class.
Java anonymous inner classes are useful when we need only one object of the class.
Since an anonymous inner class does not have a name, it cannot have a constructor because
we know a constructor name is the same as the class name.
Then how do we create an object of an anonymous class in Java if it does not have a
constructor? Let’s understand this concept.
How to create Object of Anonymous inner class in Java?
Basically, an anonymous inner class in Java is a one-time class. We can define an anonymous
inner class and create its object using the new operator at the same time in one step.
The general syntax to create anonymous inner class and its object in java is as follows:
Syntax:
new<interface-name or class-name>(argument-list)
{
// Anonymous class body
}
Key points:
1. The new keyword is used to create an object of the anonymous inner class. It is always
followed by either an existing class name or an existing interface name.
2. In the above syntax, if an interface name is used, it means that the anonymous class
implements the interface.
3. If a class name is used, it means that the anonymous class extends from the class.
4. If the new keyword is followed by a class name then the argument list is used only. The
argument list contains the actual parameter list which is used for calling a constructor of the
existing class.
5. If the new keyword is followed by an interface name, it is left empty.
6. Inside an anonymous class body, we can define variables, methods (if necessary), instance
block, and local class.
Java Anonymous Inner Class Constructor
Since an anonymous inner class has no name, it is not possible to define a constructor for it
within the class body.
When to use Anonymous Inner class in Java?
In general, there are the following points that you should consider using an anonymous inner
class instead of a local inner class.
1. The main purpose of using an anonymous inner class in java is just for instant use (i.e. one-
time usage).
2. An anonymous inner class can be used if the class has a very short body.
3. It can be useful if only one object of the class is required.
4. An anonymous inner class is useful when you are writing implementation classes for
listener interfaces in graphics programming.
5. An anonymous inner class is the best suitable for GUI based applications to implement
event handling.
Note:
1. If the requirement is standard and required several times, then you should go for a normal
top-level class.
2. If the requirement is temporary and required only once (instant use), you should go for the
anonymous inner class.
Features of Anonymous Inner Class
An anonymous inner class in Java is a special kind of inner class with the following
important features. They are as follows:
1. When an anonymous inner class is created, internally, its name is decided by the compiler
which always extends a superclass or implements an interface. But it cannot have an explicit
extends or implements clause.
2. It must implement all the abstract methods defined within a superclass or of the interface.
3. Internally, it always uses a default constructor from its superclass to create an object.
4. An anonymous inner class is compiled by a class named OuterClassName$n. For example,
if the outer class Student has two anonymous inner classes, they are compiled into
Student$[Link] and Student$[Link].
5. Like the local inner class, an anonymous inner class can also access the members of its
outer class.
Types of Anonymous Inner Class in Java
Based on declaration and behavior, an anonymous inner class in Java comes into two flavors.
They are as follows:
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface
Let’s understand them with the help of example programs one by one.
Anonymous inner class that extends class
Let’s take an example program in which we will declare an anonymous inner class that
extends a class Fruits. Look at the source code to understand better.
Program code 1:
package anonymousClass;
public class Fruits
{
public void mango()
{
[Link]("Sweet");
}
// Suppose we also declared here 9 more types of fruits method. So, the
total number of fruits method is 10.
}
Suppose we need a sour mango in taste for a one time (temporary requirement). Except for
this method, the remaining 9 methods we also want as it is. Then how will you implement
this in the above code?
There are two ways by which we can implement inside the above code.
1. First way is that we will create a class that will extend the Fruits class and overrides the
mango method. But this technique is suitable for the permanent requirement, not for the
temporary requirement.
2. Second way is that we will use an anonymous inner class concept for a one-time temporary
requirement.
package anonymousClass;
public class Taste {
public static void main(String[] args)
{
// Here, we are using an anonymous inner class that extends a class Fruits.
Fruits f = new Fruits()
{
// Here, Overriding the mango() method of Fruits class.
public void mango()
{
[Link]("Sour"); // Overriding.
}
}; // Anonymous inner class ends here. A semi-colon is necessary to end
the statement.
[Link]();
// This object is created for Fruits class.
Fruits f1 = new Fruits();
[Link](); // It will print sweet.
}
}
Output:
Sour
Sweet
Internal working of given code:
Fruits f = new Fruits()
{
public void mango()
{
[Link]("Sour"); // Overriding.
}
}; // Anonymous inner class ends here.
1. In line 1, Fruits f = new Fruits() { tells us that an object of the anonymous class is created
that is referred by a reference variable f of type Fruits.
Then declare a new class but its name is decided by the compiler that extends the fruits class
and provides the implementation (i.e overriding) of mango() method.
In line 1, there is also a curly brace that opens the class definition.
2. In line 2, within the new class definition, we are overriding the mango() method of the
superclass Fruits.
3. In line 4, Statement within the overriding mango() method.
4. In line 5, we are closing curly brace of the mango() method.
5. Line 6 includes a curly brace closing off the anonymous inner class definition. But curly
brace also contains a semicolon that ends the statement started on line 1.
Reference: Scientech Easy, [Link]
[Link]/, retrieved 29/03/2023.
Static import in Java
From Java 1.5 and above, with the help of static import, we can access the static members of
a class directly without class name or any object. For Example: we always use sqrt() method
of Math class by using Math class i.e. [Link](), but by using static import we can access
sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance coding.
But according to the programming experts, it will lead to confusion and not good for
programming. If there is no specific requirement then we should not go for static import.
Advantage of static import:
If user wants to access any static member of class then less coding is required.
Disadvantage of static import:
Static import makes the program unreadable and unmaintainable if you are reusing this
feature.
// Java Program to illustrate
// calling of predefined methods
// without static import
class Geeks {
public static void main(String[] args)
{
[Link]([Link](4));
[Link]([Link](2, 2));
[Link]([Link](6.3));
}
}
Output:
2.0
4.0
6.3
// Java Program to illustrate
// calling of predefined methods
// with static import
import static [Link].*;
class Test2 {
public static void main(String[] args)
{
[Link](sqrt(4));
[Link](pow(2, 2));
[Link](abs(6.3));
}
}
Output:
2.0
4.0
6.3
// Java to illustrate calling of static member of
// System class without Class name
import static [Link].*;
import static [Link].*;
class Geeks {
public static void main(String[] args)
{
// We are calling static member of System class
// directly without System class name
[Link](sqrt(4));
[Link](pow(2, 2));
[Link](abs(6.3));
}
}
Output:
2.0
4.0
6.3
NOTE : System is a class present in [Link] package and out is a static variable present in
System class. By the help of static import we are calling it without class name.
Ambiguity in static import:
If two static members of the same name are imported from multiple different classes, the
compiler will throw an error, as it will not be able to determine which member to use in the
absence of class name qualification.
// Java program to illustrate
// ambiguity in case of
// static import
import static [Link].*;
import static [Link].*;
public class Geeks {
public static void main(String[] args)
{
[Link](MAX_VALUE);
}
}
Output:
Error:Reference to MAX_VALUE is ambiguous
Explanation : In the above program, we are trying to access MAX_VALUE variable, but
Every primitive data type contains MAX_VALUE variable which is pre-declared in there
Wrapper class. Here we are importing Integer and Byte class simultaneously and trying to
access static variable MAX_VALUE but here compiler will be confused by seeing two
import statements because both Integer and Byte class contains a static variable
MAX_VALUE. Therefore here compiler throw an error saying Reference to MAX_VALUE
is ambiguous.
NOTE : Two package contains two class/interface with the same name is very rare.
Therefore it is very rare that we will get any ambiguity while importing normal way i.e.
normal import. But it is possible that two classes contains same variable, therefore it is very
common in static import to get error saying reference is ambiguous. Thats why it is not
recommended to use if there is no such requirement.