Professional Documents
Culture Documents
Session 11
Session 11
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
nl
However, there are several cases when it becomes mandatory for an object to
O
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
en
C
h
ec
pt
rA
Fo
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
Interfaces are stored in packages and the bytecode file is stored in a directory
Fo
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
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
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
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
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
*/
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 members
Fo
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
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
/**
* Overridden method, applies brake to a vehicle
Fo
*
* @return void
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
* @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
if(args.length==3) {
Fo
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
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
/**
* Abstract method to call the manufacturer
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
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
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
System.out.println(“Applying brakes...”);
}
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
{
System.out.println(“Vehicle No.: “+ STATEID+ “ “+ ID);
Fo
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
*/
rA
@Override
public void callManufacturer(String phone) {
Fo
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
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
}
rA
}
}
Fo
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
U
tre
en
C
h
ec
pt
rA
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
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
An abstract class can inherit from another An interface can extend from one or more
Fo
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
encapsulation.
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
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
• Nesting of small classes within larger top-level classes helps to place the code
closer to where it will be used.
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
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
To instantiate an inner class, one must create an instance of the outer class.
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
* @return void
*/
rA
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
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
en
C
h
ec
pt
rA
Fo
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
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
*/
public void evaluateStatus(String empID, int empAge){
Fo
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
}
rA
}
Fo
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
}
}
Fo
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
}
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
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
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
Since, an anonymous class does not have a name, it cannot have a named
rA
Rules for accessing an anonymous class are the same as that of local inner class.
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
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
+ “ 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
}
}
© 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
U
tre
en
C
h
ec
pt
rA
Fo
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
package session11;
import java.util.Calendar;
rA
class AtmMachine {
/**
Fo
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
System.out.println(“Date-Time:” + objNow.getTime());
}
Fo
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) {
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
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
*
*/
Fo
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
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
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