OOP Java Module 2 - 22022023
OOP Java Module 2 - 22022023
Module 2
Contents:
Inheritance - Types of Inheritance - Superclass and subclass - calling super class constructor
and methods - overloading vs overriding - Final variables, final methods and final classes - Abstract
methods and class - polymorphism - dynamic binding - Visibility controls.
Interfaces - Definition - Extending, Implementing and accessing Interfaces- packages -
Creating and Accessing Packages.
Courtesy:
Balagurusamy E: “Programming with Java”, 3e/5e, and some web resources.
INHERITANCE:
One of the important concepts of an Object-Oriented language is code reusability. Java does
this using a concept known as inheritance. It allows us to inherit the properties of one class into
another class. The existing (old) class is known as base class or superclass or parent class. The new
class is known as a derived class or subclass or child class. It allows us to use the properties
(attributes) and behavior (methods) of one class (parent) in another class (child). In addition to the
inherited attributes and methods, the child class can add new attributes and methods.
Types of Inheritance
1. Single Inheritance:
In single inheritance, a subclass is derived from only one super class. It inherits the properties
and behavior of a single-parent class. Sometimes it is also known as simple inheritance.
Syntax:
Example:
class Room
{
int length, breadth;
Room(int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return length*breadth;
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x, int y, int z)
{
super(x,y); // to call parent constructor
height = z;
}
int volume()
{
return (length*breadth*height);
}
}
class SingleInheritance
{
public static void main (String[] args)
{
BedRoom room1 = new BedRoom(7,6,8);
int area1 = room1.area();
int volume1 = room1.volume();
System.out.println("Area = " + area1);
System.out.println("Volume = " + volume1);
}
}
2. Multilevel Inheritance:
If class B is inherited from class A and if class C is inherited from class B, this type of
inheritance is called multilevel inheritance. The chain ABC is called the inheritance path.
Syntax:
Class A
{
…..
}
Class B extends A // First level
{
…..
}
Class C extends B // Second level
{
…..
}
3. Hierarchical Inheritance:
Hierarchical Inheritance a combination of more than one type of inheritance. Here a number of
classes are derived from a single base class.
OVERRIDING METHODS
A method defined in a superclass is inherited by its subclass and is used by the objects created
by the subclass. Method inheritance enables us to define and use them repeatedly in subclasses
without having to define the methods again in subclasses. Sometimes we need to modify the
superclass method in subclass. On those occasions we can define new modified methods with the
same name as that in the parent. This feature is called method overriding.
Sample format:
class A
{
void methodname1()
{ ..body1..}
S4 CT - OOP Java - Module 2 Page 4 of 18
}
class B extends A
{
void methodname1() // overrides the method of parent
{ ..body2..}
}
Here the method methodname1() is redefined (overridden) in the child class B. For an object of class
A, the body1 is executed and for that of B, body2 is executed.
Example:
class Room
{
int length, breadth;
Room(int x, int y)
{
length=x;
breadth=y;
}
void display()
{
System.out.println ("Room: Length="+ length+ ", breadth=" + breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x, int y, int z)
{
super(x,y); // to call parent constructor
height = z;
}
void display()
{
System.out.println ("BedRoom: Length=" +length +", breadth="+
breadth +", Height="+height);
}
}
class MethodOverriding
{
public static void main (String[] args)
{
BedRoom room1 = new BedRoom(7,6,8);
room1.display(); // calls child class method
OVERRIDING VS OVERLOADING:
Overriding Overloading
Occurs between superclass and subclass Occurs between the methods in the same class
Have the same signature (name and method Have the same name, but the parameters are
arguments) different
The method call is determined at runtime based The method call is determined at compile time
on the object type
On error, the effect will be visible at runtime On error, it can be caught at compile time
FINAL CLASSES:
If we make a class final by adding the keyword final before the class definition, the class
cannot be inherited further.
Eg: final class Aclass { ……. }
final class Bclass extends someclass { …… }
FINALIZER METHODS:
These are just opposite to constructors. A constructor is called when an object is created.
Similarly a finalizer method is called when the object is freed by the garbage collector. If we do not
specify the finalizer method, the system will define one and free the object memory. If we define the
finalizer method in the class by using the finalize( ) keyword, the system will call this method only
and we have to explicitly define what to do.
b=new ICICI();
System.out.println("ICICI Rate: " + b.getRateOfInterest());
b=new AXIS();
S4 CT - OOP Java - Module 2 Page 8 of 18
System.out.println("AXIS Rate: " + b.getRateOfInterest());
}
}
INTERFACES
Inheriting a subclass from more than one superclass is called multiple inheritance. Java does
not allow multiple inheritance directly, as it increases the complexity. Instead, it can be implemented
using interfaces.
Defining Interfaces:
An interface is basically a kind of class. It contains variables and methods. But the difference is
that, in interfaces the methods are abstract methods (does not have a body), and the data fields contain
only constants (static final variables). Therefore it is the duty of the subclass that implements the
interface to define the code for implementation of these methods. An interface can be defined using
the keyword interface.
Syntax:
interface InterfaceName
{
variables declaration; // static final by default
Methods declaration; // abstract by default
}
Eg:
S4 CT - OOP Java - Module 2 Page 9 of 18
interface Item
{
static final int code = 1001;
String name = “Fan”; // static final by default
abstract void setData(int a);
void display( ); // abstract by default
}
Extending Interfaces:
Like classes, interfaces also can be extended. That is an interface can be subinterfaced from
other interfaces. The new subinterface will inherit all the members of the superinterface similar to
subclasses. This is achieved using the keyword extends as shown below.
interface name1
{
Body of name1
}
interface name2 extends name1
{
Body of name2
}
For example, we can put all the constants in one interface and the methods in the other. This
will enable us to use the constants in classes where the methods are not required.
Example:
interface ItemConstants
{
int code = 1001;
String name = “Fan”;
}
interface Item extends ItemConstants
S4 CT - OOP Java - Module 2 Page 10 of 18
{
void display( );
}
Implementing Interfaces
Classes can be inherited from interfaces. This is done using the keyword implements.
Syntax:
class className implements interface1
{
…
}
Also, these classes can be extended from other classes at the same time.
class className extends superclass implements interface1, interface2, …
{
…
}
Example:
interface Area // interface defined
{
float pi = 3.14F; // final static by default
float compute (float x, float y); // abstract by default
}
class InterfaceTest
{
public static void main (String[] args)
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
interface AnimalEat
{
void eat();
}
interface AnimalTravel
{
void travel();
}
PACKAGES:
A package in Java is a group of a variety of classes and/or interfaces together. The grouping is
usually done according to functionality. By importing predefined/created packages to our program, we
can use the classes in them without recreating them. Thus packages help in code reuse. As the
packages are containers, classes of different packages can have the same name.
Java packages are classified into two types; user defined packages and Java API packages
such as swing, util, net, io, AWT, lang, etc.
Java API
It provides a large number of classes grouped into different packages according to
functionality. Some common packages are given below.
The packages are organized in a hierarchical structure. The outermost one is the java package
which contains several other packages such as awt packages, which contains a number of classes such
as the Color class. This class can have different useful methods also, that we can use. For example,
the getBlue( ) method of Color class. In this example, the Color class can be referred to as
java.awt.Color.
To use the package, its class or their methods, we have to first import them to our program.
The import statements are given at the top of the program. This is done by;
import packagename.classname; // import the particular class
or
import packagename.*; // imports all classes in the package
Eg:
import java.awt.Color; // imports the class Color of awt package
import java.awt.*; // imports all classes of awt package
S4 CT - OOP Java - Module 2 Page 15 of 18
Naming Convention:
● Package names start with lowercase letters. (eg: lang)
● Class names inside the packages start with uppercase letters. (eg: Math)
● Methods inside the classes start with lowercase letters. (eg: sqrt(x) )
● Example of a fully qualified representation of imported classes and methods;
double y = java.lang.Math.sqrt(x);
This statement calls the sqrt() method of the Math class of the lang package, and
returns the square-root of the variable x.
Creating a package
The first statement of a package must be the package name. This is declared by the keywork
package.
Eg:
package packagename;
Then we create the classes as usual. The classes must be public so that other programs can access
them.
Eg:
package firstPackage;
public class FirstClass
{
…..
}
The package files must be stored in a directory which has the same name as the package. When
compiled, the class files will also be stored there. The newly created package directory has to be
present in the directory where the programs that import this package are residing. If not, the package
directory must be accessible through the java path variables.
Package names and directory structure are closely related. For example if a package name is
college.staff.cse, then there are three directories, college, staff and cse such that cse is present in staff
and staff is present college.
There can be more than one public class in a package, but each public class needs to be
declared in its own .java file. If you want these public classes that are in different .java files to be
contained in the same package, simply put package mypack; at the very beginning of these .java files.
This is the example, how you should name these files:
1. Box.java:
package mypack;
public class Box {...}
2. Circle.java:
package mypack;
public class Circle {...}
Note that files should be named with the name of the public class contained in it (if public
class is present inside).
Accessing a Package:
S4 CT - OOP Java - Module 2 Page 16 of 18
Packages can be included in the program using the import keyword. The general syntax is;
import package1[.package2][.package3].classname;
Here package1 is the name of the top level package, package2 is the name of the package that
is inside package1, and so on. We can have any number of packages in the package-hierarchy. Finally
the class name to be imported is specified. This is followed by a semicolon. The import statement
must appear before any class definitions in a source file. Multiple import statements are allowed.
import packagename.*;
This imports all packages or classes under the package packagename. This broad approach is
used only when a number of packages or classes are to be imported from a specific package.
Package Example:
Problem: Create a package named testpackage with two classes; PackClassA and PackClassB. The
PackClassA can have a method to return the largest factor of a given two digit positive integer. The
PackClassB can have two methods; one to return the square of a given integer and the other to return
the cube of a given integer. Import this package to a new program and find the cube of a number and
largest factor of a number. Also find the square root of a given number using built-in packages.
Solution: Create a directory named testpackage. Inside this, write the two classes PackClassA and
PackClassB as two java files with names PackClassA.java and PackClassB.java. The classes and
methods must be public. Then write the main class program outside, but along with this directory.
//PackClassA.java
package testpackage;
//PackClassB.java
package testpackage;
Here in the two java files, the first statement is package testpackage; so as to specify that the two files
come under the same package. The main methods can be included in both files to test the files
individually, but after creation the main method is not mandatory and can be avoided. This is because,
when these classes are imported to another java program, that program will have the main method.
When compiling both the java files, the .class files will be created along with the source files, inside
the testpackage directory. We can write the main java program just outside this directory, but along
with this directory.
// main class
import testpackage.*; // importing all the classes of testpackage
class TestPackageSub
{
public static void main(String [] args)
{
int x = testpackage.PackClassB.cube(3);
System.out.println ("Cube of 3 is "+x);
x = testpackage.PackClassA.largestFactor(50);
System.out.println ("Largest Factor of 50 is "+x);
}
}