Java Inheritance: Types and Benefits
Java Inheritance: Types and Benefits
me/jntuh
UNIT – II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using final
with inheritance, polymorphism- method overriding, abstract classes, the Object class. Defining, Creating
and Accessing a Package, Understanding CLASSPATH, importing packages, differences between classes
and interfaces, defining an interface, implementing interface, applying interfaces, variables in interface
and extending interfaces. Exploring [Link].
INHERITANCE IN JAVA
Inheritance is an important pillar of OOP(Object-Oriented Programming).
The process of obtaining the data members and methods from one class to another class is known
as inheritance.
Important Terminologies Used in Java Inheritance
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base
class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Why Do We Need Java Inheritance?
Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved through
inheritance. Abstraction only shows the functionality to the user.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java.
Using the extends keyword indicates you are derived from an existing class. In other words, “extends”
refers to increased functionality.
Syntax
class SubclassName extends SuperclassName
{
//methods and ields
}
Example
class Animal
{
String name;
void show()
{
[Link](“Animal name is:"+name);
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Barking");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]="DOG";
[Link]();
[Link]();
}
}
isinglet
multiple
Single
Example
In the example, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
class Animal
{
String name;
void show()
{
[Link]("Animal Name is"+name);
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Mother Dog Barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
[Link]("Baby Dog weeping");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]="MotherDog";
[Link]();
[Link]();
[Link]();
}
}
Example
class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class Cat extends Animal
{
void meow()
{
[Link]("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}
}
The concept of multiple inheritance is not supported in java through concept of classes but it can be
supported through the concept of interface.
5. Hybrid inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces.
SUBSTITUTABILITY
The inheritance concept used for the number of purposes in the java programming language. One of
the main purposes is substitutability.
01
The substitutability means that when a child class acquires properties from its parent class, the object
of the parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect an instance of A we can use an instance of
B.
The substitutability can achieve using inheritance, whether using extends or implements keywords.
MEME_
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the
principle of substitutability.
Speci ication
This is another commonly used form of inheritance. In this form of inheritance, the parent class just
c
speci ies which methods should be available to the child class but doesn't implement them. The java
provides concepts like abstract and interfaces to support this form of inheritance. It holds the principle
of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior de ined by the parent
class (overriding). It does not hold the principle of substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It holds the principle
of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold
the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent classes.
Java does not support multiple inheritance type.
d
ACCESS CONTROL(MEMBER ACCESS)
In Java, Access modi iers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modi ier used with
the element.
Festrictthe
Types of Access Modi iers in Java
There are four types of access modi iers available in Java:
class courts
Scope
1. Default – No keyword required
2. Private
of
variable method
3. Protected data member
4. Public
1. Default Access Modi ier
Paresthesia
When no access modi ier is speci ied for a class, method, or data member – It is said to be having
the default access modi ier by default.
The default modi ier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more restrictive than protected, and public.
D
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by [Link]
package pack;
class A
{
void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
mT
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
[Link](); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
2. private
The private access modi ier is accessible only within the class.
The private access modi ier is speci ied using the keyword private.
The methods or data members declared as private are accessible only within the class in which
they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
F
{
[Link]("Hello java");}
}
[Link]
{
public static void main(String args[])
1 iaI
{
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}
}
3. protected
The protected access modi ier is accessible within package and outside the package but through
inheritance only.
The protected access modi ier is speci ied using the keyword protected .
Example
In β this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by [Link]
package pack;
public class A
iron {
protected void msg()
{
[Link]("Hello");
Yetan
}
}
error
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
Private YES NO NO NO
0
derived class the base class data members must be preceded by super keyword.
Syntax
[Link] datamember name
Example
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
F
{
[Link](color); //prints color of Dog class
[Link]([Link]); //prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
1 [Link]();
}
}
same
}
}
class Dog extends Animal
{
void eat()
{
[Link]("eating bread...");
}
void dispay()
{
eat();
[Link]();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}
3. Super keyword At Constructor Level
The super keyword can also be used to invoke the parent class constructor.
class Animal
{
Animal()
{
[Link]("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
[Link]("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
1
{
Dog d=new Dog();
}
}
1
{
[Link]("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
[Link]("drawing circle");
}
}
class TestAbstraction1
{
static void main(String args[])
{
Shape s=new Circle1();
[Link]();
}
}
Return
Method Description
Value
hashCode() returns the hashcode number for object being used. int
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds void
and nanoseconds, until another thread notifies.
If you omit the package statement, the class names are put into the default package, which has no
name.
Syntax
package packagename;
Example
package mypack;
Compile package programs
For compilation of package program irst we save program with public [Link] and it compile
using below syntax:
Syntax
[Link]
javac -d . [Link] javas d class
Explanation
In above syntax "-d" is a speci ic tool which tells to java compiler create a separate folder for the given
package in given path.
When we give speci ic path then it create a new folder at that location and when we use . (dot) then it
crate a folder at current working directory.
Note: Any package program can be compile but can not be execute or run. These program can be
executed through user de ined program which are importing package program.
Example of Package Program
Package program which is save with [Link] and compile by javac -d . [Link].
package mypack;
public class A
{
public void show()
{
[Link]("Sum method");
}
}
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A implements Printable,Showable
{
public void print()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}
public static void main(String args[])
{
A obj = new A();
[Link]();
[Link]();
}
}
o
In Java, streams are the sequence of data that are read from the source and written to the destination.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. [Link]: This is the standard input stream that is used to read characters from the keyboard or
any other standard input device.
2. [Link]: This is the standard output stream that is used to produce the result of a program on
an output device like the computer screen.
e
3. [Link]: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS
Depending on the type of operations, streams can be divided into two primary classes:
InPutStream − The InputStream is used to read data from a source.
In
Java byte streams are used to perform input and output of 8-bit bytes.
Byte Stream Classes
All byte stream classes are derived from base abstract classes called InputStream and OutputStream.
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of
bytes.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
Stream class Description
F
Character Stream Classes
All the character stream classes are derived from base abstract classes Reader and Writer.
Reader Class
The Reader class of the [Link] package is an abstract super class that represents a stream of characters.
Sub classes of Reader Class
In order to use the functionality of Reader, we can use its subclasses. Some of them are:
Stream class Description
BufferedReader Handles buffered input stream.
FileReader Input stream that reads from file.
InputStreamReader Input stream that translate byte to character
Methods of Reader
The Reader class provides different methods that are implemented by its subclasses. Here are
some of the commonly used methods:
ready() - checks if the reader is ready to be read
read(char[] array) - reads the characters from the stream and stores in the speci ied array
read(char[] array, int start, int length) - reads the number of characters equal to length from the
stream and stores in the speci ied array starting from the start
mark() - marks the position in the stream up to which data has been read
reset() - returns the control to the point in the stream where the mark is set
skip() - discards the speci ied number of characters from the stream
E
Writer Class
The Writer class of the [Link] package is an abstract super class that represents a stream of
characters.
Since Writer is an abstract class, it is not useful by itself. However, its subclasses can be used to write
data.
Subclasses of Writer
Stream class Description
BufferedWriter Handles buffered output stream.
FileWriter Output stream that writes to ile.
PrintWriter Output Stream that contain print() and println() method.
Methods of Writer
The Writer class provides different methods that are implemented by its subclasses. Here are
some of the methods:
write(char[] array) - writes the characters from the speci ied array to the output stream
write(String data) - writes the speci ied string to the writer
append(char c) - inserts the speci ied character to the current writer
lush() - forces to write all the data present in the writer to the corresponding destination
close() - closes the writer