Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

OOP Java Module 2 - 22022023

Uploaded by

Dhanya R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

OOP Java Module 2 - 22022023

Uploaded by

Dhanya R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Object-Oriented Programming (Java)

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.

Deriving a subclass from superclass is done by using the keyword extend.


A subclass is defined as follows:
Class subclassname extends superclassname
{
Variable declaration;
Method declaration;
}

S4 CT - OOP Java - Module 2 Page 1 of 18


Different types of inheritance in Java are;
1. Single Inheritance (only one superclass).
2. Multilevel inheritance (derived from a derived class).
3. Hierarchical inheritance (one superclass, many subclasses).
4. Multiple Inheritance (several superclasses) - Java does not directly implement this. But does
this through interfaces.

Some points to note:


● Constructor cannot be inherited in Java.
● Private members do not get inherited in Java.
● Cyclic inheritance is not permitted in Java.
● Constructors can be executed using the keyword super( ) present in the child constructor.

The super( ) keyword:


A subclass constructor is used to construct the instance variables of both subclass and
superclass variables. It uses the keyword super to to invoke its parent class constructor. This keyword
must be used in the subclass constructor only. The call to superclass constructor must appear as the
first statement within the subclass constructor. The parameters in the super call must match that in the
superclass constructor.

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:

S4 CT - OOP Java - Module 2 Page 2 of 18


class A
{
…..
}
class B extends A
{
…..
}

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);
}
}

S4 CT - OOP Java - Module 2 Page 3 of 18


Output:
Area = 42
Volume = 336

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

Room room2 = new Room(6,5);


room2.display(); // calls parent class method
}
}
S4 CT - OOP Java - Module 2 Page 5 of 18
Output:
BedRoom: Length=7, breadth=6,Height=8
Room: Length=6, breadth=5

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

Implements “runtime polymorphism” Implements “compile time polymorphism”

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 METHODS AND VARIABLES:


All child classes can override the methods of the parent class. If we wish to prevent the
subclasses from overriding the members of the superclass, we can declare them as final using the
keyword final. If the final keyword is applied to variables, their values cannot be changed later. Final
variables belong to the class and do not take space in objects.
Eg: final int SIZE=100;
final void display( ) { …….. }

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.

ABSTRACT METHODS AND CLASSES:


Abstract does the opposite of what final does. Final keyword represents that the method cannot
be redefined (overridden) in the subclass, whereas an abstract method means that the method must be
redefined in the subclass. That means, overriding that method is compulsory. If a class contains an
abstract method, that class also should be declared as abstract. The abstract methods will not have a
body. It is represented as just a declaration.

S4 CT - OOP Java - Module 2 Page 6 of 18


Syntax:
abstract class classname
{

abstract ret-type methodname ( parameters);

}

Features of abstract class and methods:


● Objects cannot be created from abstract classes.
For example, if Shape is an abstract class, then
Shape obj = new Shape( ) will generate an error.
● Abstract classes can have abstract and normal methods.
● The abstract methods of an abstract class must be redefined in the subclass.
● We cannot declare abstract constructors or abstract static methods.
Example:
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others

class Rectangle extends Shape


{
void draw( )
{ System.out.println("drawing rectangle"); }
}

class Circle extends Shape


{
void draw( )
{ System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction
{
public static void main(String args[])
{
Shape c=new Circle( );
c.draw();
Shape r=new Rectangle( );
r.draw();
}
}

This will give the output;


drawing circle
drawing rectangle

S4 CT - OOP Java - Module 2 Page 7 of 18


POLYMORPHISM:
Polymorphism in Java is a concept by which we can perform a single action in different ways. There
are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.
1. Compile-time Polymorphism: It is also known as static polymorphism. This type of
polymorphism is achieved by Method Overloading. When there are multiple methods with the
same name but different parameters then these methods are said to be overloaded. Methods can
be overloaded by changes in the number of arguments or/and a change in the type of
arguments. (For example, see module 1: Method overloading)
2. Runtime Polymorphism: This type of polymorphism is achieved by Method Overriding.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. This is also called
Dynamic Binding. In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Example for Runtime Polymorphism:


class Bank
{
float getRateOfInterest()
{return 0;}
}
class SBI extends Bank
{
float getRateOfInterest()
{return 8.4f;}
}
class ICICI extends Bank
{
float getRateOfInterest()
{return 7.3f;}
}
class AXIS extends Bank
{
float getRateOfInterest()
{return 9.7f;}
}
class MethodOverriding2
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("SBI Rate: " +
b.getRateOfInterest());

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());
}
}

This will give the output;


SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Visibility controls: (Discussed in Module 1)

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
}

Difference between class and interface

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( );
}

We can also combine several interfaces together into a single interface.


interface ItemConstants
{
int code = 1001;
String name = “Fan”;
}
interface ItemMethods
{
void display( );
}
interface Item extends ItemConstants, ItemMethods
{
….
}
An interface cannot be extended from a class.

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, …
{

}

The class has to redefine all the methods in the interfaces.

S4 CT - OOP Java - Module 2 Page 11 of 18


● Interface can be extended from one or more interfaces
● Class can be extended from one or more interfaces and/or classes
● Class can be extended from one or more interfaces
● Interface cannot be extended from classes

Example:
interface Area // interface defined
{
float pi = 3.14F; // final static by default
float compute (float x, float y); // abstract by default
}

class Rectangle implements Area


{
public float compute (float x, float y) //overriding the abstract method
{
return (x*y);
}
}

class Circle implements Area

S4 CT - OOP Java - Module 2 Page 12 of 18


{
public float compute (float x, float y) //overriding the abstract
method
{
return (pi*x*x);
}
}

class InterfaceTest
{
public static void main (String[] args)
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();

System.out.println ("Rectangle Area is " + rect.compute(3,2));


System.out.println ("Circle Area is " + cir.compute(3,0));
// only x is needed for the circle. Hence put y as 0
}
}

This will give the output;


Rectangle Area is 6.0
Circle Area is 28.26

Accessing Interface Variables (Use of Interface Variables)


Interfaces can be used to declare a set of constants that can be used in different classes. This is
similar to creating header files in C++ to contain a large number of objects. Since such interfaces do
not contain methods, there is no need to worry about implementing any methods. The constant values
will be available to any class that implements the interface. The values can be used in any method as
part of any variable declaration, or anywhere where we can use a final value.
Eg:
interface A
{
int m = 10;
int n = 50;
}
class B implements A
{
int x = m; // using interface variable m
void methodB (int size)
{
………………….
………………….
If (size < n) // using interface variable n
…..
}
}

S4 CT - OOP Java - Module 2 Page 13 of 18


Multiple Inheritance Example in Java

interface AnimalEat
{
void eat();
}

interface AnimalTravel
{
void travel();
}

class Animal implements AnimalEat, AnimalTravel


{
public void eat() // overriding
{
System.out.println("Animal is eating");
}
public void travel() // overriding
{
System.out.println("Animal is traveling");
}
}

public class MultipleInheritanceTest


{
public static void main(String args[])
{
Animal a = new Animal();
a.eat();
a.travel();
}
}

The output will be;


Animal is eating
Animal is traveling

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.

We use package for the following reasons:


● The package makes the search easier for the classes and interfaces.
● It provides a fully qualified name that avoids naming conflicts.
S4 CT - OOP Java - Module 2 Page 14 of 18
● It also controls access.
● It organizes classes in a folder structure.
● It improves code reusability.
● Programmers can group classes and interfaces into a related package.

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;

public class PackClassA


{
public static int largestFactor(int a)
{
if(a<1 && a>99)
{
System.out.println("You must enter an integer between 0 and 100");
return -1;
}
else
{
int max=1;
for (int i=2; i<a; i++)
if(a%i==0)
max=i;
return max;
}
}
}

//PackClassB.java
package testpackage;

public class PackClassB


{
public static int square(int a)

S4 CT - OOP Java - Module 2 Page 17 of 18


{
return a*a;
}

public static int cube(int a)


{
return a*a*a;
}
}

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);
}
}

S4 CT - OOP Java - Module 2 Page 18 of 18

You might also like