Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Fo

rA
pt
ec
h
C
en
tre
U
se
O
Fundamentals of Java

nl
y
y
Describe Interface

nl

O
 Explain the purpose of interfaces

se
 Explain implementation of multiple interfaces

U
 Describe Abstraction

tre
 Explain Nested class
Explain Member class

en

 Explain Local class


Explain Anonymous classC
h

ec

 Describe Static nested class


pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 2


y
Java does not support multiple inheritance.

nl

However, there are several cases when it becomes mandatory for an object to

O

inherit properties from multiple classes to avoid redundancy and complexity

se
in code.

U
 For this purpose, Java provides a workaround in the form of interfaces.
Also, Java provides the concept of nested classes to make certain types of

tre

programs easy to manage, more secure, and less complex.

en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 3


y
nl
An interface in Java is a contract that specifies the standards to be followed by
the types that implement it.

O
se
 The classes that accept the contract must abide by it.
An interface and a class are similar in the following ways:

U

tre
An interface can contain multiple methods.

en
C
An interface is saved with a .java extension and the name of the file must match
with the name of the interface just as a Java class.
h
ec

The bytecode of an interface is also saved in a .class file.


pt
rA

Interfaces are stored in packages and the bytecode file is stored in a directory
Fo

structure that matches the package name.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 4


y
 An interface and a class differ in several ways as follows:

nl
O
se
An interface
cannot be

U
instantiated.

tre
An interface cannot have
constructors.

en
All the methods of an interface are
implicitly abstract.

C
The fields declared in an interface must be
h
both static and final.
ec

Interface cannot have instance fields.


pt
rA

An interface is not extended but implemented by a class.


Fo

An interface can extend multiple interfaces.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 5


y
In several situations, it becomes necessary for different groups of developers to

nl
agree to a ‘contract’ that specifies how their software interacts.

O
Each group should have the liberty to write their code in their desired manner

se
without having the knowledge of how the other groups are writing their code.

U
tre
Java interfaces can be used for defining such contracts.

en
Interfaces do not belong to any class hierarchy, even though they work in
conjunction with classes.
C
h
Java does not permit multiple inheritance for which interfaces provide an
ec

alternative.
pt

In Java, a class can inherit from only one class but it can implement multiple
rA

interfaces.
Fo

Therefore, objects of a class can have multiple types such as the type of their own
class as well as the types of the interfaces that the class implements.
© Aptech Ltd. Interfaces and Nested Classes/Session 11 6
y
 The syntax for declaring an interface is as follows:

nl
Syntax

O
<visibility> interface <interface-name> extends <other-interfaces, … >

se
{

U
// declare constants
// declare abstract methods

tre
}

where,

en
<visibility>: Indicates the access rights to the interface. Visibility of an
interface is always public.
C
<interface-name>: Indicates the name of the interface.
h
ec
<other-interfaces>: List of interfaces that the current interface inherits from.
For example,
pt

public interface Sample extends Interface1{


rA

static final int someInteger;


public void someMethod();
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 7


y
 In Java, interface names are written in CamelCase, that is, first letter of each word is

nl
capitalized.

O
 Also, the name of the interface describes an operation that a class can perform. For
example,

se
interface Enumerable

U
interface Comparable

tre
 Some programmers prefix the letter ‘I’ with the interface name to distinguish
interfaces from classes. For example,

en
interface IEnumerable
interface Icomparable
C
Notice that the method declaration does not have any braces and is terminated with a
h

semicolon.
ec

 Also, the body of the interface contains only abstract methods and no concrete
pt

method.
rA

 Since all methods in an interface are implicitly abstract, the abstract keyword is
not explicitly specified with the method signature.
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 8


y
 Consider the hierarchy of vehicles where IVehicle is the interface that declares the

nl
methods which the implementing classes such as TwoWheeler, FourWheeler, and

O
so on can define.
 To create a new interface in NetBeans IDE, right-click the package name and select

se
New → Java Interface as shown in the following figure:

U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 9


y
 A dialog box appears where the user must provide a name for the interface and then,

nl
click OK. This will create an interface with the specified name.

O
 Following code snippet defines the interface, IVehicle:

se
package session11;
public interface IVehicle {

U
// Declare and initialize constant

tre
static final String STATEID=”LA-09”; // variable to store state ID

en
/**
* Abstract method to start a vehicle
* @return void
C
h
*/
ec
public void start();
pt

/**
rA

* Abstract method to accelerate a vehicle


* @param speed an integer variable storing speed
* @return void
Fo

*/
public void accelerate(int speed);
© Aptech Ltd. Interfaces and Nested Classes/Session 11 10
y
/**

nl
* Abstract method to apply a brake

O
* @return void
*/

se
public void brake();

U
/**
* Abstract method to stop a vehicle

tre
* @return void
*/

en
public void stop();
}
C
The syntax to implement an interface is as follows:
h

ec

Syntax
pt

class <class-name> implements <Interface1>,…


rA

{
// class members
Fo

// overridden abstract methods of the interface(s)


}

© Aptech Ltd. Interfaces and Nested Classes/Session 11 11


Following code snippet defines the class TwoWheeler that implements the

y

nl
IVehicle interface:

O
package session11;
class TwoWheeler implements IVehicle {

se
String ID; // variable to store vehicle ID

U
String type; // variable to store vehicle type

tre
/**
* Parameterized constructor to initialize values based on user input

en
*

C
* @param ID a String variable storing vehicle ID
* @param type a String variable storing vehicle type
h
*/
ec

public TwoWheeler(String ID, String type){


this.ID = ID;
pt

this.type = type;
rA

}
Fo

/**
* Overridden method, starts a vehicle
*
© Aptech Ltd. Interfaces and Nested Classes/Session 11 12
y
* @return void

nl
*/

O
@Override
public void start() {

se
System.out.println(“Starting the “+ type);
}

U
/**

tre
* Overridden method, accelerates a vehicle
* @param speed an integer storing the speed

en
* @return void
*/
@Override
C
h
public void accelerate(int speed) {
ec

System.out.println(“Accelerating at speed:”+speed+ “ kmph”);


}
pt
rA

/**
* Overridden method, applies brake to a vehicle
Fo

*
* @return void

© Aptech Ltd. Interfaces and Nested Classes/Session 11 13


y
*/

nl
@Override

O
public void brake() {
System.out.println(“Applying brakes”);

se
}

U
/**
* Overridden method, stops a vehicle

tre
*
* @return void

en
*/
@Override
public void stop() {
C
h
System.out.println(“Stopping the “+ type);
ec

}
pt

/**
rA

* Displays vehicle details


*
Fo

* @return void
*/
public void displayDetails(){
© Aptech Ltd. Interfaces and Nested Classes/Session 11 14
y
System.out.println(“Vehicle No.: “+ STATEID+ “ “+ ID);

nl
System.out.println(“Vehicle Type.: “+ type);

O
}
}

se
/**

U
* Define the class TestVehicle.java

tre
*
*/

en
public class TestVehicle {

/**
C
* @param args the command line arguments
h
*/
ec

public static void main(String[] args){


pt

// Verify the number of command line arguments


rA

if(args.length==3) {
Fo

// Instantiate the TwoWheeler class


TwoWheeler objBike = new TwoWheeler(args[0], args[1]);

© Aptech Ltd. Interfaces and Nested Classes/Session 11 15


y
// Invoke the class methods

nl
objBike.displayDetails();

O
objBike.start();
objBike.accelerate(Integer.parseInt(args[2]));

se
objBike.brake();
objBike.stop();

U
}

tre
else {
System.out.println(“Usage: java TwoWheeler <ID> <Type> <Speed>”);

en
}
}
}
C
h
 Following figure shows the output of the code when the user passes CS-2723 Bike
ec
80 as command line arguments:
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 16


y
 Java does not support multiple inheritance of classes but allows implementing multiple

nl
interfaces to simulate multiple inheritance.

O
 To implement multiple interfaces, write the interface names after the implements
keyword separated by a comma.

se
 For example,

U
public class Sample implements Interface1, Interaface2{
}

tre
 Following code snippet defines the interface IManufacturer:

en
package session11;
public interface IManufacturer {

C
h
/**
ec
* Abstract method to add contact details
* @param detail a String variable storing manufacturer detail
pt

* @return void
*/
rA

public void addContact(String detail);


Fo

/**
* Abstract method to call the manufacturer

© Aptech Ltd. Interfaces and Nested Classes/Session 11 17


y
* @param phone a String variable storing phone number

nl
* @return void

O
*/
public void callManufacturer(String phone);

se
/**

U
* Abstract method to make payment
* @param amount a float variable storing amount

tre
* @return void
*/

en
public void makePayment(float amount);

C
} h
 The modified class, TwoWheeler implementing both the IVehicle and
ec
IManufacturer interfaces is displayed in the following code snippet:
pt

package session11;
class TwoWheeler implements IVehicle, IManufacturer {
rA

String ID; // variable to store vehicle ID


Fo

String type; // variable to store vehicle type

© Aptech Ltd. Interfaces and Nested Classes/Session 11 18


y
/**

nl
* Parameterized constructor to initialize values based on user input

O
*
* @param ID a String variable storing vehicle ID

se
* @param type a String variable storing vehicle type
*/

U
public TwoWheeler(String ID, String type){
this.ID = ID;

tre
this.type = type;
}

en
/**
C
* Overridden method, starts a vehicle
h
*
ec

* @return void
*/
pt

@Override
rA

public void start() {


System.out.println(“Starting the “+ type);
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 19


y
/**

nl
* Overridden method, accelerates a vehicle

O
* @param speed an integer storing the speed
* @return void

se
*/
@Override

U
public void accelerate(int speed) {

tre
System.out.println(“Accelerating at speed:”+speed+ “ kmph”);
}

en
C
/**
* Overridden method, applies brake to a vehicle
h
*
ec

* @return void
*/
pt

@Override
rA

public void brake() {


Fo

System.out.println(“Applying brakes...”);
}

© Aptech Ltd. Interfaces and Nested Classes/Session 11 20


y
/**

nl
* Overridden method, stops a vehicle

O
*
* @return void

se
*/
@Override

U
public void stop() {

tre
System.out.println(“Stopping the “+ type);
}

en
C
/**
* Displays vehicle details
h
*
ec

* @return void
*/
pt

public void displayDetails()


rA

{
System.out.println(“Vehicle No.: “+ STATEID+ “ “+ ID);
Fo

System.out.println(“Vehicle Type.: “+ type);


}

© Aptech Ltd. Interfaces and Nested Classes/Session 11 21


y
// Implement the IManufacturer interface methods

nl
O
/**
* Overridden method, adds manufacturer details

se
* @param detail a String variable storing manufacturer detail
* @return void

U
*/
@Override

tre
public void addContact(String detail) {
System.out.println(“Manufacturer: “+detail);

en
}

/** C
h
* Overridden method, calls the manufacturer
ec

* @param phone a String variable storing phone number


* @return void
pt

*/
rA

@Override
public void callManufacturer(String phone) {
Fo

System.out.println(“Calling Manufacturer @: “+phone);


}

© Aptech Ltd. Interfaces and Nested Classes/Session 11 22


y
/**

nl
* Overridden method, makes payment

O
* @param amount a String variable storing the amount
* @return void

se
*/
@Override

U
public void makePayment(float amount) {
System.out.println(“Payable Amount: $”+amount);

tre
}
}

en
/**
C
* Define the class TestVehicle.java
h
*
ec

*/
public class TestVehicle {
pt

/**
rA

* @param args the command line arguments


*/
Fo

public static void main(String[] args){


// Verify number of command line arguments
if(args.length==6) {
© Aptech Ltd. Interfaces and Nested Classes/Session 11 23
y
// Instantiate the class

nl
TwoWheeler objBike = new TwoWheeler(args[0], args[1]);

O
objBike.displayDetails();
objBike.start();

se
objBike.accelerate(Integer.parseInt(args[2]));
objBike.brake();

U
objBike.stop();
objBike.addContact(args[3]);

tre
objBike.callManufacturer(args[4]);
objBike.makePayment(Float.parseFloat(args[5]));

en
}

C
else{ h
// Display an error message
ec

System.out.println(“Usage: java TwoWheeler <ID> <Type> <Speed>


<Manufacturer> <Phone> <Amount>”);
pt

}
rA

}
}
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 24


y
 The class TwoWheeler now implements both the interfaces; IVehicle and

nl
IManufacturer as well as all the methods of both the interfaces.

O
 Following figure shows the output of the modified code.
The user passes CS-2737 Bike 80 BN-Bikes 808-283-2828 300 as

se

command line arguments.

U
tre
en
C
h
ec
pt
rA

 The interface IManufacturer can also be implemented by other classes such as


Fo

FourWheeler, Furniture, Jewelry, and so on, that require manufacturer


information.
© Aptech Ltd. Interfaces and Nested Classes/Session 11 25
y
nl
Abstraction is defined as the process of hiding the unnecessary details and

O
revealing only the essential features of an object to the user.

se
Abstraction is a concept that is used by classes that consist of attributes and

U
methods that perform operations on these attributes.

tre
Abstraction can also be achieved through composition. For example, a class Vehicle
is composed of an engine, tyres, ignition key, and many other components.

en
C
In Java, abstract classes and interfaces are used to implement the concept of
abstraction.
h
ec

To use an abstract class or interface one needs to extend or implement


abstract methods with concrete behavior.
pt
rA

Abstraction is used to define an object based on its attributes, functionality, and


interface.
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 26


y
 The differences between an abstract class and an interface are listed in the following

nl
table:

O
Abstract Class Interface

se
An abstract class can have abstract as

U
An interface can have only abstract
well as concrete methods that are methods
methods.

tre
with a body.

en
An abstract class may have non-final Variables declared in an interface are
variables. implicitly final.

C
An abstract class may have members with
Members of an interface are public by
h
different access specifiers such as private,
default.
ec

protected, and so on.


pt

An abstract class is inherited using the An interface is implemented using the


extends keyword. implements keyword.
rA

An abstract class can inherit from another An interface can extend from one or more
Fo

class and implement multiple interfaces. interfaces.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 27


y
 Some of the differences between Abstraction and Encapsulation are as follows:

nl
Abstraction refers to bringing out the behavior from ‘How exactly’ it is

O
implemented whereas Encapsulation refers to hiding details of implementation
from the outside world so as to ensure that any change to a class does not affect

se
the dependent classes.

U
Abstraction is implemented using an interface in an abstract class whereas

tre
Encapsulation is implemented using private, default or package-private, and
protected access modifier.

en
C
h
Encapsulation is also referred to as data hiding.
ec
pt
rA

The basis of the design principle ’programming for interface than


implementation’ is abstraction and that of ’encapsulate whatever changes’ is
Fo

encapsulation.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 28


y
 Java allows defining a class within another class.

nl
 Such a class is called a nested class as shown in the following figure:

O
se
U
tre
en

C
Following code snippet defines a nested class:
h
class Outer{
ec

...
class Nested{
pt

...
rA

}
}
Fo

 The class Outer is the external enclosing class and the class Nested is the class
defined within the class Outer.
© Aptech Ltd. Interfaces and Nested Classes/Session 11 29
Nested classes are classified as static and non-static.

y

nl
 Nested classes that are declared static are simply termed as static nested

O
classes whereas non-static nested classes are termed as inner classes.
 This has been demonstrated in the following code snippet:

se
class Outer{

U
...
static class StaticNested{

tre
...
}

en
class Inner{
...
}
C
h
}
ec

 The class StaticNested is a nested class that has been declared as static
whereas the non-static nested class, Inner, is declared without the keyword
pt

static.
rA

 A nested class is a member of its enclosing class.


Fo

 Non-static nested classes or inner classes can access the members of the enclosing
class even when they are declared as private.
 Static nested classes cannot access any other member of the enclosing class.
© Aptech Ltd. Interfaces and Nested Classes/Session 11 30
The reasons for introducing this advantageous feature of defining nested class in Java

y

nl
are as follows:

O
Creates logical grouping of classes

se
• If a class is of use to only one class, then it can be embedded within that class and
the two classes can be kept together.

U
• In other words, it helps in grouping the related functionality together.

tre
• Nesting of such ‘helper classes’ helps to make the package more efficient and
streamlined.

en
Increases encapsulation

C
• In case of two top level classes such as class A and B, when B wants access to
members of A that are private, class B can be nested within class A so that B
h
can access the members declared as private.
ec

• Also, this will hide class B from the outside world.


• Thus, it helps to access all the members of the top-level enclosing class even if
pt

they are declared as private.


rA

Increased readability and maintainability of code


Fo

• Nesting of small classes within larger top-level classes helps to place the code
closer to where it will be used.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 31


y
 The different types of nested classes are as follows:

nl
O
Member classes or

se
non-static nested classes

U
tre
Local classes

en
Anonymous classes
C
h
Static Nested classes
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 32


y
nl
A member class is a non-static inner class.

O
It is declared as a member of the outer or enclosing class.

se
The member class cannot have static modifier since it is associated with instances of the

U
outer class.

tre
An inner class can directly access all members that is, fields and methods of the outer class
including the private ones.

en
However, the outer class cannot access the members of the inner class directly even if they
are declared as public.

C
This is because members of an inner class are declared within the scope of inner class.
h
ec

An inner class can be declared as public, private, protected, abstract, or final.


pt
rA

Instances of an inner class exist within an instance of the outer class.


Fo

To instantiate an inner class, one must create an instance of the outer class.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 33


y
 One can access the inner class object within the outer class object using the statement

nl
defined in the following code snippet:

O
// accessing inner class using outer class object
Outer.Inner objInner = objOuter.new Inner();

se
 Following code snippet describes an example of non-static inner class:

U
package session11;

tre
class Server {
String port; // variable to store port number

en
/**

C
* Connects to specified server
*
h
* @param IP a String variable storing IP address of server
ec

* @param port a String variable storing port number of server


pt

* @return void
*/
rA

public void connectServer(String IP, String port) {


Fo

System.out.println(“Connecting to Server at:”+ IP + “:” + port);


}

© Aptech Ltd. Interfaces and Nested Classes/Session 11 34


y
/**

nl
* Define an inner class

O
*
*/

se
class IPAddress
{

U
/**
* Returns the IP address of a server

tre
*
* @return String

en
*/
String getIP() {
C
return “101.232.28.12”;
h
}
ec

}
}
pt
rA

/**
* Define the class TestConnection.java
Fo

*
*/
public class TestConnection {
© Aptech Ltd. Interfaces and Nested Classes/Session 11 35
y
/**

nl
* @param args the command line arguments

O
*/
public static void main(String[] args){

se
/**
* @param args the command line arguments

U
*/
public static void main(String[] args)

tre
{
// Check the number of command line arguments

en
if(args.length==1) {
// Instantiate the outer class
C
Server objServer1 = new Server();
h
// Instantiate the inner class using outer class object
ec

Server.IPAddress objIP = objServer1.new IPAddress();


// Invoke the connectServer() method with the IP returned from
pt

// the getIP() method of the inner class


rA

objServer1.connectServer(objIP.getIP(),args[0]);
}
Fo

else {
System.out.println(“Usage: java Server <port-no>”); }
}}
© Aptech Ltd. Interfaces and Nested Classes/Session 11 36
y
 The class Server is an outer class that consists of a variable port that represents the

nl
port at which the server will be connected.

O
 Also, the connectServer(String, String) method accepts the IP address
and port number as a parameter.

se
 The inner class IPAddress consists of the getIP() method that returns the IP

U
address of the server.
Following figure shows the output of the code when user provides ‘8080’ as the port

tre

number at command line:

en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 37


y
An inner class defined within a code block such as the body of a method, constructor, or an

nl
initializer, is termed as a local inner class.

O
The scope of a local inner class is only within that particular block.

se
Unlike an inner class, a local inner class is not a member of the outer class and therefore, it

U
cannot have any access specifier.

tre
That is, it cannot use modifiers such as public, protected, private, or static.

en
However, it can access all members of the outer class as well as final variables declared
within the scope in which it is defined.


C
Following figure displays a local inner class:
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 38


y
 Local inner class has the following features:

nl
 It is associated with an instance of the enclosing class.

O
 It can access any members, including private members, of the enclosing class.

se
 It can access any local variables, method parameters, or exception parameters that
are in the scope of the local method definition, provided that these are declared as

U
final.

tre
 Following code snippet demonstrates an example of local inner class.
package session11;

en
class Employee {

/**
C
* Evaluates employee status
h
*
ec

* @param empID a String variable storing employee ID


pt

* @param empAge an integer variable storing employee age


* @return void
rA

*/
public void evaluateStatus(String empID, int empAge){
Fo

// local final variable


final int age=40;

© Aptech Ltd. Interfaces and Nested Classes/Session 11 39


y
/**

nl
* Local inner class Rank

O
*
*/

se
class Rank{

U
/**
* Returns the rank of an employee

tre
*
* @param empID a String variable that stores the employee ID

en
* @return char
*/
C
public char getRank(String empID){
h
System.out.println(“Getting Rank of employee: “+ empID);
ec

// assuming that rank ‘A’ was returned from server


return ‘A’;
pt

}
rA

}
Fo

// Check the specified age


if(empAge>=age){

© Aptech Ltd. Interfaces and Nested Classes/Session 11 40


y
// Instantiate the Rank class

nl
Rank objRank = new Rank();

O
// Retrieve the employee’s rank

se
char rank = objRank.getRank(empID);

U
// Verify the rank value
if(rank == ‘A’) {

tre
System.out.println(“Employee rank is:”+ rank);
System.out.println(“Status: Eligible for upgrade”);

en
}

C
else{
System.out.println(“Status: Not Eligible for upgrade”);
h
}
ec

}
else{
pt

System.out.println(“Status: Not Eligible for upgrade”);


rA

}
}
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 41


y
/**

nl
* Define the class TestEmployee.java

O
*
*/

se
public class TestEmployee {

U
/**
* @param args the command line arguments

tre
*/
public static void main(String[] args)

en
{
if(args.length==2) {
C
// Object of outer class
h
Employee objEmp1 = new Employee();
ec

// Invoke the evaluateStatus() method


objEmp1.evaluateStatus(args[0], Integer.parseInt(args[1]));
pt

}
rA

else{
System.out.println(“Usage: java Employee <Emp-Id> <Age>”);
Fo

}
}
}
© Aptech Ltd. Interfaces and Nested Classes/Session 11 42
y
 The class Employee is the outer class with a method named

nl
evaluateStatus(String,int).

O
 The class Rank is a local inner class within the method.
The Rank class consists of one method getRank() that returns the rank of the

se

specified employee Id.

U
 If the age of the employee is greater than 40, the object of Rank class is created and
the rank is retrieved.

tre
 If the rank is equal to ‘A’ then, the employee is eligible for upgrade otherwise the

en
employee is not eligible.
 Following figure shows the output of the code when user passes ‘E001’ as employee
Id and 50 for age:
C
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 43


y
nl
An inner class declared without a name within a code block such as the body
of a method is called an anonymous inner class.

O
se
An anonymous class does not have a name associated, so it can be accessed only at
the point where it is defined.

U
tre
It cannot use the extends and implements keywords nor can specify any
access modifiers, such as public, private, protected, and static.

en
It cannot define a constructor, static fields, methods, or classes.
C
h
It cannot implement anonymous interfaces because an interface cannot be
ec

implemented without a name.


pt

Since, an anonymous class does not have a name, it cannot have a named
rA

constructor but it can have an instance initializer.


Fo

Rules for accessing an anonymous class are the same as that of local inner class.

© Aptech Ltd. Interfaces and Nested Classes/Session 11 44


y
 Usually, anonymous class is an implementation of its super class or interface and

nl
contains the implementation of the methods.

O
 Anonymous inner classes have a scope limited to the outer class.
They can access the internal or private members and methods of the outer class.

se

 Anonymous class is useful for controlled access to the internal details of another class.

U
 Also, it is useful when a user wants only one instance of a special class.

tre
 Following figure displays an anonymous class:

en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 45


Following code snippet describes an example of anonymous class:

y

nl
package session11;
class Authenticate {

O
/**

se
* Define an anonymous class
*

U
*/
Account objAcc = new Account() {

tre
/**
* Displays balance

en
*
* @param accNo a String variable storing balance
* @return void
C
h
*/
ec
@Override
public void displayBalance(String accNo) {
pt

System.out.println(“Retrieving balance. Please wait...”);


rA

// Assume that the server returns 40000


System.out.println(“Balance of account number “ + accNo.toUpperCase()
Fo

+ “ is $40000”);
}
© Aptech Ltd. Interfaces and Nested Classes/Session 11 46
y
}; // End of anonymous class

nl
}

O
/**
* Define the Account class

se
*
*/

U
class Account {
/**

tre
* Displays balance
*

en
* @param accNo a String variable storing balance
* @return void
*/
C
h
public void displayBalance(String accNo) {
ec

}
}
pt
rA

/**
* Define the TestAuthentication class
Fo

*
*/
public class TestAuthentication {
© Aptech Ltd. Interfaces and Nested Classes/Session 11 47
y
/**

nl
* @param args the command line arguments

O
*/
public static void main(String[] args) {

se
// Instantiate the Authenticate class
Authenticate objUser = new Authenticate()

U
// Check the number of command line arguments

tre
if (args.length == 3) {
if (args[0].equals(“admin”) && args[1].equals(“abc@123”)){

en
// Invoke the displayBalance() method
objUser.objAcc.displayBalance(args[2]);
}
else{ C
h
System.out.println(“Unauthorized user”);
ec

}
}
pt

else {
rA

System.out.println(“Usage: java Authenticate <user-name> <password>


<account-no>”);
}
Fo

}
}
© Aptech Ltd. Interfaces and Nested Classes/Session 11 48
y
 The class Authenticate consists of an anonymous object of type Account.

nl
 The displayBalance(String) method is used to retrieve and display the

O
balance of the specified account number.
Following figure shows the output of the code when user passes ‘admin’, ‘abc@123’,

se

and ‘akdle26152’, as arguments:

U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 49


y
A static nested class is associated with the outer class just like variables and

nl
methods.

O
A static nested class cannot directly refer to instance variables or methods of the

se
outer class just like static methods but can access only through an object reference.

U
A static nested class, by behavior, is a top-level class that has been nested in
another top-level class for packaging convenience.

tre
Static nested classes are accessed using the fully qualified class name, that is,

en
OuterClass.StaticNestedClass.

C
A static nested class can have public, protected, private, default or
package private, final, and abstract access specifiers.
h
ec

 Following code snippet demonstrates the use of static nested class:


pt

package session11;
import java.util.Calendar;
rA

class AtmMachine {
/**
Fo

* Define the static nested class


*

© Aptech Ltd. Interfaces and Nested Classes/Session 11 50


y
*/

nl
static class BankDetails

O
{
// Instantiate the Calendar class of java.util package

se
static Calendar objNow = Calendar.getInstance();

U
/**
* Displays the bank and transaction details

tre
*
* @return void

en
*/

C
public static void printDetails(){
System.out.println(“State Bank of America”);
h
System.out.println(“Branch: New York”);
ec

System.out.println(“Code: K3983LKSIE”);
pt

// retrieving current date and time using Calendar object


rA

System.out.println(“Date-Time:” + objNow.getTime());
}
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 51


y
/**

nl
* Displays balance

O
* @param accNo a String variable that stores the account number
* @return void

se
*/
public void displayBalance(String accNo) {

U
// Assume that the server returns 200000
System.out.println(“Balance of account number “ + accNo.toUpperCase()

tre
+
“ is $200000”);

en
}
}

C
h
/**
ec
* Define the TestATM class
*
pt

*/
public class TestATM {
rA

/**
* @param args the command line arguments
Fo

*/
public static void main(String[] args) {

© Aptech Ltd. Interfaces and Nested Classes/Session 11 52


y
if(args.length ==1) { // verifying number of command line arguments

nl
// Instantiate the outer class

O
AtmMachine objAtm = new AtmMachine();
// Invoke the static nested class method using outer class object

se
AtmMachine.BankDetails.printDetails();
// Invoke the instance method of outer class

U
objAtm.displayBalance(args[0]);
}

tre
else{
System.out.println(“Usage: java AtmMachine <account-no>”);

en
}

C
}
}
h
ec
 Following figure shows the output of the code when user passes ‘akdle26152’ as
account number:
pt
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 53


y
 Notice that the output of date and time shows the default format as specified in the

nl
implementation of the getTime() method.

O
 The format can be modified according to the user requirement using the
SimpleDateFormat class of java.text package.

se
 SimpleDateFormat is a concrete class used to format and parse dates in a

U
locale-specific manner.
SimpleDateFormat class allows specifying user-defined patterns for date-time

tre

formatting.

en
 The modified BankDetails class using SimpleDateFormat class is displayed in
the following code snippet:
C
import java.text.SimpleDateFormat;
h
import java.util.Calendar;
ec

class AtmMachine {
/**
pt

* Define the static nested class


rA

*
*/
Fo

static class BankDetails {


// Instantiate the Calendar class of java.util package
static Calendar objNow = Calendar.getInstance();
© Aptech Ltd. Interfaces and Nested Classes/Session 11 54
y
/**

nl
* Displays the bank and transaction details
*

O
* @return void

se
*/
public static void printDetails(){

U
System.out.println(“State Bank of America”);
System.out.println(“Branch: New York”);

tre
System.out.println(“Code: K3983LKSIE”);

en
// Format the output of date-time using SimpleDateFormat class
SimpleDateFormat objFormat = new SimpleDateFormat(“dd/MM/yyyy
HH:mm:ss”);
C
h
ec
// Retrieve the current date and time using Calendar object
System.out.println(“Date-Time:” +
pt

objFormat.format(objNow.getTime()));
rA

}
}

Fo


}
© Aptech Ltd. Interfaces and Nested Classes/Session 11 55
y
 The SimpleDateFormat class constructor takes the date pattern as a String.

nl
 In the code, the pattern dd/MM/yyyy HH:mm:ss uses several symbols that are

O
pattern letters recognized by the SimpleDateFormat class.
Following table lists the pattern letters used in the code with their description:

se

U
tre
en

C
Following figure shows the output of the modified code:
h
ec
pt
rA
Fo

 The date and time are now displayed in the specified format that is more understandable
to the user.
© Aptech Ltd. Interfaces and Nested Classes/Session 11 56
y
 An interface in Java is a contract that specifies the standards to be followed by the

nl
types that implement it.

O
 To implement multiple interfaces, write the interfaces after the implements keyword
separated by a comma.

se
 Abstraction, in Java, is defined as the process of hiding the unnecessary details and

U
revealing only the necessary details of an object.
Java allows defining a class within another class. Such a class is called a nested class.

tre

 A member class is a non-static inner class. It is declared as a member of the outer or

en
enclosing class.
 An inner class defined within a code block such as the body of a method, constructor,
C
or an initializer, is termed as a local inner class.
h
 An inner class declared without a name within a code block such as the body of a
ec

method is called an anonymous inner class.


pt

 A static nested class cannot directly refer to instance variables or methods of the outer
class just like static methods but only through an object reference.
rA
Fo

© Aptech Ltd. Interfaces and Nested Classes/Session 11 57

You might also like