Java-Unit 2 Inheritance and Polymorphism
Java-Unit 2 Inheritance and Polymorphism
Unit-2
Inheritance and Polymorphism: Inheritance in java, Super and sub class, Overriding, Object
class, Polymorphism, Dynamic binding, Generic programming, Casting objects, Instance of operator,
Abstract class, Interface in java, Package in java, UTIL package.
Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally, Collections in java, Introduction to
JavaBeans and Network Programming.
INHERITANCE IN JAVA
INHERITANCE:EXTENDING A CLASS
Java does not directly implement multiple inheritance. However, this concept
is implemented using a secondary inheritance path in the form of interfaces.
Defining a subclass:
A sub class is defined as:
Class subclassname extends superclassname
variable declaration;
methods declaration;
The keyword extends signifies that the properties of the super classname are
extended to the subclassname. (or) The extends keyword indicates that you are
making a new class that derives from an existing class. The meaning of "extends"
is to increase the functionality. The subclass will now contain its own variables
and methods as well those of the [Link] kind of situation occurs when we
want to add some more properties to an existing class without actually modifying
it.
class Animal
{
void eat()
{
[Link]("eating...");
Void bark()
[Link](“barking…”);}
Class TestInheritance
[Link]();
Output:
Barking… eating…
Or
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
SHWETHA RANI R S 1ST BCA Page 5
OBJECT ORIENTED PROGRAMMING WITH JAVA
multilevel inheritance.
General form
class baseclass
{
…..//data members
……//member functions
}
class derivedclass-1 extends baseclass
{
…..//data members
……//member functions
}
class derivedclass-2 extends derivedclass-1
{
…..//data members
……//member functions
}
Example programme
File: [Link]
Class Animal
Void eat()
[Link](“eating…”);
Void bark()
[Link](“barking…”);
}
SHWETHA RANI R S 1ST BCA Page 6
OBJECT ORIENTED PROGRAMMING WITH JAVA
Void weep()
[Link](“weeping…”);
Class TestInheritance2
[Link]();
[Link]();
Output
Weeping…
Barking….
Eating……
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
SHWETHA RANI R S 1ST BCA Page 7
OBJECT ORIENTED PROGRAMMING WITH JAVA
General form
Class baseclass
…..//data members
……//member functions
…..//data members
……//member functions
…..//data members
……//member functions
}
Example programme
Class Animal
Void eat()
[Link](“eating…”);
Void bark()
[Link](“barking…”);
Void meow()
[Link](“meowing…”);
Class TestInheritance3
[Link]();
//[Link]();//[Link]
}}
Output:
meowing...
eating...
The program defines a class room and extends it to another class bedroom. Note
that the class bedroom defines its own data members and [Link] sub class
bedroom now includes three instance variables, namely length, breadth and
height and two methods area and volume.
The constructor in the derived class uses the super keyword to pass values
SHWETHA RANI R S 1ST BCA Page 11
OBJECT ORIENTED PROGRAMMING WITH JAVA
calls first the bedroom constructor method, which in turn calls the room
constructor method by using the super keyword. Finally the object room1 of the
subclass bedroom calls the method area defines in the super class as well as the
method volume defined in the subclass itself.
Subclass constructor:
A subclass constructor is used to construct the instance variables of both the subclass
and the [Link] subclass constructor uses the keyword super to invoke the
Constructor method of the [Link] keyword super is used subject to the
following conditions:
• The call to super class constructor must appear as the first statement
within the subclass constructor.
• The parameters in the super call must match the order and type of the
instance variable declared in the super class.
OVERRIDING METHODS:
Defining a method in the subclass that has the same name, same arguments and same return
type as a method in the superclass.
When the method is called, the method defined in the subclass is invoked and executed
instead of the one in the superclass.
(or)
However, there may be occasions when we want an object to respond to the same method but
have different behaviour when that method is called. That means, we should override the method
defined in the super class. This is possible by defining a method in the subclass that has the same name,
same arguments and same return type as a method in the super class. Then, when that method is called,
the method defined in the sub class is invoked and executed instead of the one in the superclass. This
is known as overriding
SHWETHA RANI R S 1ST BCA Page 12
OBJECT ORIENTED PROGRAMMING WITH JAVA
any type like Employee, Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();
The Object class provides some common behaviors to all the objects such as object can be compared, object
can be cloned, object can be notified etc.
• toString() Method
• hashCode() Method
• equals(Object obj) Method
• getClass() method
• finalize() method
• clone() method
• wait(), notify() notifyAll() Methods
toString() Method:
It's provide string representation or convert object to string form. you can override toString() method
to get your own String representation of objects.
public String toString()
{
// Can override and give own definition
}
hashCode() Method:
It's generate unique hashcode for each object. The main advantage of saving objects. It's used to
override for user defined objects for better performance like searching.
equals(Object obj) Method:
It's used to compare the two objects dynamically.
getClass() Method:
It's return runtime class object and used to get metadata information as well.
finalize() method:
This method call required to perform garbage collector.
clone() method:
It used to create the copy or clone of object.
wait(), notify() notifyAll() Methods:
These are used in multithreading.
POLYMORPHISM IN JAVA
The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic
A person at the same time can have different characteristics. Like a man at the same time is a father,
a husband, an employee. So the same person possesses different behavior in different situations. This
is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to define one interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.
Types of polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism
Method Overloading: When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change in
the number of arguments or/and a change in the type of arguments.
Example 1
// Java Program for Method overloading
// By using Different Types of Arguments
class Helper {
{
return a * b; // Returns product of integer numbers
}
// Method 2
{
return a * b; // Returns product of double numbers
}
}
// Class 2
// Main class
class GFG {
{
// Calling method by passing
// input as in arguments
[Link]([Link](2, 4));
[Link]([Link](5.5, 6.3));
}
}
Output:
8
34.65
Type 2: Runtime polymorphism
Casting objects
Upcasting and Downcasting in Java
A process of converting one data type to another is known
as Typecasting and Upcasting and Downcasting is the type of object typecasting. In Java, the
object can also be typecast like the datatypes. Parent and Child objects are two types of objects.
So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to
Parent or can say Upcasting and Downcasting.
Typecasting is used to ensure whether variables are correctly processed by a function or not.
In Upcasting and Downcasting, we typecast a child object to a parent object and a parent object
to a child object simultaneously. We can perform Upcasting implicitly or explicitly, but downcasting
cannot be implicitly possible.
1) Upcasting
Upcasting is a type of object typecasting in which a child object is typecasted to a parent class
object. By using the Upcasting, we can easily access the variables and methods of the parent class to
the child class. Here, we don't access all the variables and the method. We access only some specified
variables and methods of the child class. Upcasting is also known as Generalization and Widening.
[Link]
class Parent{
void PrintData()
void PrintData()
}
SHWETHA RANI R S 1ST BCA Page 18
OBJECT ORIENTED PROGRAMMING WITH JAVA
class UpcastingExample
[Link]();
[Link]();
2) Downcasting
Upcasting is another type of object typecasting. In Upcasting, we assign a parent class reference object
to the child class. In Java, we cannot assign a parent class reference object to the child class, but if we
perform downcasting, we will not get any compile-time error. However, when we run it, it throws
the "ClassCastException". Now the point is if downcasting is not possible in Java, then why is it
allowed by the compiler? In Java, some scenarios allow us to perform downcasting. Here, the subclass
object is referred by the parent class.
Below is an example of downcasting in which both the valid and the invalid scenarios are explained:
[Link]
//Parent class
class Parent {
String name;
void showMessage()
int age;
void showMessage()
[Link] = "Shubham";
Child c = (Child)p;
[Link] = 18;
[Link]([Link]);
[Link]([Link]);
[Link]();
GENERIC PROGRAMMING
The Java Generics programming is introduced to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the
collection, i.e., non-generic. Now generics force the java programmer to store a specific type of
objects.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that work with different data types. An entity such as class, interface, or method that
operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any object. These
features lack type safety. Generics add that type of safety feature. We will discuss that type of safety
feature in later examples
Types of Java Generics
Generic Method: Generic Java method takes a parameter and returns some value after performing a
task. It is exactly like a normal function, however, a generic method has type parameters that are
cited by actual type. This allows the generic method to be used in a more general way. The compiler
takes care of the type of safety which enables programmers to code easily since they do not have to
perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of parameter,
separated by a comma. The classes, which accept one or more parameters, are known as
parameterized classes or parameterized types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a
generic class, we use the following syntax.
// To create an instance of generic class
Test(T obj)
{
[Link] = obj; } // constructor
public T getObject()
{
return [Link];
}
SHWETHA RANI R S 1ST BCA Page 21
OBJECT ORIENTED PROGRAMMING WITH JAVA
{
Test<Integer> iObj = new Test<Integer>(15); // instance of Integer type
[Link]([Link]());
[Link]([Link]());
}}
Output
15
BCA
Instance of operator
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
[Link](s instanceof Simple1); //true
}
}
Output:true
ABSTRAT CLASSES:
If the class acts as base class for many other classes and is not useful on its own, then we can
avoid instantiation and only it's declaration is enough. This is achieved by using abstract
keyword. Similarly we can have only method declaration and allow derived class to define it by
using abstract keyword. Such class is called abstract class and such method is called abstract
method. It can have abstract and non-abstract methods (method with the body).
We have seen that by making a method final we ensure that the method is not
redefined in a sub class. That is, the method can never be sub classed. Java allows us to
do something that is exactly opposite to this. That is, we can indicate that a method must
always be redefined in a sub class, thus making overriding compulsory. This is done using
the modifier keyword abstract in the method definition.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
[Link]("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}
Output:
running safely
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
When a class contains one or more abstract methods, it should also be declared
Abstract as shown in the example above.
INTERFACE IN JAVA
INTERFACES:MULTIPLE INHERITANCE
Java does not support multiple inheritance. That is, classes in Java cannot
have more than one superclass. For instance, a definition like:
.............................
.............................
Is not permitted in Java.a large number of real-life applications require the use of
multiple inheritance where by we inherit methods and properties from several
distinct classes.
DEFININGINTERFACES:
Interface interfacename
variable declaration;
methods declaration;
The syntax for defining an interface is very similar to that for defining a class.
Here, interface is the keyword and interfacename is any valid Java
variable(just like class names).
Note that all variables are declared as constants.
EXTENDINGINTERFACES
Body of name2
For example, we can put all the constants in one interface and the methods in the
Interface ItemConstants
Int code=1001 ;
String name=“Fan”;
Void display();
}
other. This will enable us to use the constants in classes where the methods are
not required. Example
IMPLEMENTING INTERFACES
Interfaces are used as "superclasses" whose properties are inherited by classes. It
is therefore necessary to create a class that inherits the given interface. This is
done as follows:
class classname implements interfacename
{
body of classname.
}
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber ( )
{
[Link] (" Roll No : " + rollNumber);
}
}
class Test extends Student
float part1, part2;
void getMarks (float ml, float m2)
part1 = m1;
part2 = m2;
}
void putMarks ( )
{
[Link]("Marks obtained ");
[Link]("Part 1 = " + part 1);
[Link]("Part 2 = " + part 2);
}
}
interface Sports
{
float sportWt = [Link];
void putwt ();
}
class Results extends Test implements Sports
{
float total;
public void putWt ( )
{
[Link]("Sports Wt = " + sportWt);
}
void display ( )
{
total = partl+part2 + sportWt;
put Number();
putMarks();
putWt ();
[Link]("Total score = " + total);
}
}
class Hybrid
public static void main(String args[])
Results student1 = new Results();
[Link] (1234);
[Link] (27.5F, 33.0F);
[Link]();
JAVA PACKAGES
INTRODUCTION:
Benefits:
• The classes contained in the packages of other programs can be easily reused.
Java
FrequentlyusedAPIpackages
Packagename Contents
[Link] Language support classes. These are classes that Java compiler itself
uses and therefore they are automatically [Link] include
classes for primitive types, strings, math functions, threads
and exceptions.
//save as [Link]
package mypack;
[Link]("Welcome to package");
1. import package.*;
2. import [Link];
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B{
[Link]();
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
package pack;
public class A{
//save by [Link]
package mypack;
import pack.A;
class B{
[Link]();
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
package pack;
public class A{
//save by [Link]
package mypack;
class B{
[Link]();
[Link] Package
It contains the collections framework, legacy collection classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator,
and a bit array).
The package [Link] contains a number of useful classes and interfaces. Although the name of
the package might imply that these are utility classes, they are really more important than that. In
fact, Java depends directly on several of the classes in this package, and many programs will find
these classes indispensable. The classes and interfaces in [Link] include: