JAVA Unit - 3
UNIT - 3
Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another.
Super and Sub Class
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
• It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
JAVA Unit - 3
Types of Inheritance
Java supports the following four types of inheritance:
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Single Inheritance
➢ In single inheritance, a sub-class is derived from only one super class.
➢ It inherits the properties and behaviour of a single-parent class.
➢ It is also known as simple inheritance.
Multi-level Inheritance
➢ In multi-level inheritance, a class is derived from a class which is also derived from
another class is called multi-level inheritance.
➢ In simple words, we can say that a class that has more than one parent class is called
multi-level inheritance.
➢ Note that the classes must be at different levels. Hence, there exists a single base class
and single derived class but multiple intermediate base classes.
JAVA Unit - 3
Hierarchical Inheritance
➢ If a number of classes are derived from a single base class, it is called hierarchical
inheritance.
Hybrid Inheritance
➢ Hybrid means consist of more than one.
➢ Hybrid inheritance is the combination of two or more types of inheritance.
JAVA Unit - 3
Advantages of Inheritance
• Enhancing code modularity
• Improving code maintainability
• Facilitating polymorphism
• Promoting code flexibility
Overriding
Method Overriding in Java
➢ If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
➢ In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
➢ Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
➢ Method overriding is used for runtime polymorphism
JAVA Unit - 3
Example
class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
[Link]("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
[Link]();
}
}
Output:
Bike is running safely
Object Class
➢ Object class is present in [Link] package.
➢ Every class in Java is directly or indirectly derived from the Object class.
➢ If a class does not extend any other class then it is a direct child class of Object and
if extends another class then it is indirectly derived.
➢ Therefore the Object class methods are available to all Java classes.
➢ Hence Object class acts as a root of the inheritance hierarchy in any Java Program.
JAVA Unit - 3
Polymorphism
➢ Polymorphism in Java is a concept by which we can perform a single action in
different ways.
➢ Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
➢ There are two types of polymorphism in Java:
1. compile-time polymorphism
2. runtime polymorphism.
➢ We can perform polymorphism in java by method overloading and method overriding.
Runtime Polymorphism in Java
➢ 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.
➢ 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.
JAVA Unit - 3
Binding
➢ Connecting a method call to the method body is known as binding.
➢ There are two types of binding
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).
Dynamic Binding
➢ When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal
{
void eat()
{
[Link]("animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
[Link]("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog();
[Link]();
}
}
Output: dog is eating...
JAVA Unit - 3
Generic Programming
Advantages of Generics:
1. Code Reuse: We can write a method/class/interface once and use it for any type we want.
2. Type Safety: Generics make errors to appear compile time than at run time . Suppose you
want to create an ArrayList that store name of students, and if by mistake the programmer
adds an integer object instead of a string, the compiler allows it. But, when we retrieve this
data from ArrayList, it causes problems at runtime.
Casting Objects
➢ Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
• Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
• Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example
public class Main
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myInt); // Outputs 9
JAVA Unit - 3
[Link](myDouble); // Outputs 9.0
}
}
Narrowing Casting
➢ Narrowing casting must be done manually by placing the type in parentheses in front
of the value:
Example
public class Main
{
public static void main(String[] args)
{
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
[Link](myDouble); // Outputs 9.78
[Link](myInt); // Outputs 9
}
}
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.
Abstract Class
➢ A class which is declared with the abstract keyword is known as an abstract class
in Java.
➢ It can have abstract and non-abstract methods (method with the body).
JAVA Unit - 3
➢ It needs to be extended and its method implemented. It cannot be instantiated.
Example of abstract class
abstract class A
{
}
Abstract Method in Java
➢ A method which is declared as abstract and does not have implementation is known as
an abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract
Interface in Java
➢ An interface in Java is a blueprint of a class.
➢ It has static constants and abstract methods.
➢ The interface in Java is a mechanism to achieve abstraction.
➢ There can be only abstract methods in the Java interface, not method body.
➢ It is used to achieve abstraction and multiple inheritance in Java.
➢ In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
➢ An interface is declared by using the interface keyword.
➢ A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
JAVA Unit - 3
Example
interface Animal {
public void eat();
public void travel();
}
public class MammalInt implements Animal {
public void eat() {
[Link]("Mammal eats");
}
public void travel() {
[Link]("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
[Link]();
[Link]();
}
}
Output
Mammal eats
Mammal travels
JAVA Unit - 3
Package in Java
➢ A java package is a group of similar types of classes, interfaces and sub-packages.
➢ Package in java can be categorized in two form, built-in package and user-defined
package.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:
1) [Link]: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.
3) [Link]: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) [Link]: Contains classes for creating Applets.
5) [Link]: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) [Link]: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being the package
names.
JAVA Unit - 3
UTIL 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).
Following are the Important Classes in [Link] package :
1. ArrayList: Resizable-array implementation of the List interface.
2. Arrays: This class contains various methods for manipulating arrays (such as
sorting and searching).
3. Date: The class Date represents a specific instant in time, with millisecond
precision.
4. Scanner: A simple text scanner which can parse primitive types and strings
using regular expressions