0% found this document useful (0 votes)
32 views

Unit 2 Inheritance

Uploaded by

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

Unit 2 Inheritance

Uploaded by

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

UNIT-2

INHERITANCE, PACKAGES AND INTERFACES


Inheritance: Basic concepts - Forms of inheritance - Super key word –
Method overriding, Abstract classes, Dynamic method dispatch - The
Object class. Packages: Defining, Creating and Accessing, importing
packages. Interfaces: Defining, Implementing, Applying, Variables and
extending interfaces
INTRODUCTION
 The mechanism of deriving a new from an old one is called inheritance
 The old class is known as the base class or super class or parent class
 The new class is called the derived class or subclass or child class
 The inheritance allows subclasses to inherit all the variables and
methods of their parent classes
INHERITANCE
Inheritance is one of the key features of OOP that allows us to create a new class
from an existing class. The new class that is created is known as subclass (child
or derived class) and the existing class from where the child class is derived is
known as superclass (parent or base class)

Use of Inheritance
 Code Reusability
 Method Overriding (so runtime polymorphism can be achieved).
Forms of Inheritance
 Single inheritance [only one super class]
 Multiple inheritance [several super classes ]
 Hierarchical inheritance [ one super classes, many subclasses]
 Multilevel inheritance [derived from a derived class].
 Hybrid inheritance
 Java does not directly implement multiple inheritances but by
using the concept of secondary inheritance path in the form of
interfaces.
The diagrammatical representation of the forms of inheritance is as follows:

Terms used in Inheritance


 Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
 Sub Class/Child Class: Sub class is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
 Super Class/Parent Class: Super class is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.
The syntax of Java Inheritance
Class Subclass-name extends Superclass-name
{
//methods and fields
}
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.
EXAMPLE
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is: 40000.0
Bonus of programmer is: 10000
TYPES OF INHERITANCE IN JAVA
SINGLE INHERITANCE

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.
EXAMPLE
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[])
{ Dog d=new Dog();
d.bark();
d.eat();
}}

Output:
barking...
eating...
MULTILEVEL INHERITANCE
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 multilevel inheritance.

EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

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.

EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output
meowing...
eating...
Hybrid Inheritance in Java
A hybrid inheritance is a combination of more than one types of inheritance. For
example when class A and B extends class C & another class D extends class A
then this is a hybrid inheritance, because it is a combination of single and
hierarchical inheritance. Let me show you this diagrammatically:

C

|
---------------
↑ ↑
| |
A B

|
D
Example:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}
Output:
D

SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable.

Use of Super:
 Super is used to refer immediate parent class instance variable
 super() is used to invoke immediate parent class constructor
 super is used to invoke immediate parent class method
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.
Use 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
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use
method overriding.
EXAMPLE:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){
System.out.println("Vehicle is running");} }
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//Creating an instance of child class
Bike obj = new Bike();
//Calling the method with child class instance
obj.run();
} }
Output:
Vehicle is running

Example of Method Overriding


In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of
the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){
System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely
ABSTRACT CLASS IN JAVA
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.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.
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

Abstract class Example


//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{
public void sound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}}

Output
Woof
Dynamic method dispatch
Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time, rather than compile
time.
 When an overridden method is called through a superclass reference, Java
determines which version (superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to at the time the
call occurs. Thus, this determination is made at run time.
 At run-time, it depends on the type of the object being referred to (not
the type of the reference variable) that determines which version of an
overridden method will be executed
 A superclass reference variable can refer to a subclass object. This is
also known as upcasting. Java uses this fact to resolve calls to overridden
methods at run time.

Advantages of dynamic method dispatch


1. It allows Java to support overriding of methods, which are
important for run-time polymorphism.
2. It allows a class to define methods that will be shared by all its derived
classes, while also allowing these sub-classes to define their specific
implementation of a few or all of those methods.
3. It allows subclasses to incorporate their own methods and define their
implementation.
Example:

Let us look at an example.


class Animal
{
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
This will produce the following result −
Output
Animals can move
Dogs can walk and run

OBJECT CLASS
 The Object class is the parent class of all the classes in java by default.
In other words, it is the topmost class of java.
 The Object class is beneficial if you want to refer any object whose type
you don't know. Notice that parent class reference variable can refer the
child class object, know as upcasting.
PACKAGES
Introduction:
 Packages provide a mechanism for grouping a variety of classes and / or
interfaces together.
 Grouping is based on functionality
Benefits of Packages:
 The classes contained in the packages of other programs can be reused. In
packages, classes can be unique compared with classes in other packages.
 A package provides a way to hide classes.
Types of packages:
 Pre-defined packages or Java API packages
 User-defined packages
Java API packages:
A large number of classes grouped into different packages based on
functionality.
Examples:
 java.lang
 java.util
 java.io
 java.awt
 java.net
 java.applet etc.
Accessing Classes in a Package:
1. Fully Qualified class name: Example:java.awt.Color
2. import packagename.classname; Example: import java.awt.Color;
or
import packagename.*; Example: import java.awt.*;
Import statement must appear at the top of the file, before any class declaration
Creating Your Own Package
1. Declare the package at the beginning of a file using the form package
packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory
where the main source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory

Syntax:
package [PackageName];
public class [ClassName]
{
//Body of the class
}

Example:
package firstPackage;
public class FirstClass
{
//Body of the class
}

Example:
//Class in package package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
//Importing class from package import p1.*;
class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA();
obA.displayA();
}}

Creating Packages:
 Consider the following declaration: package firstPackage.secondPackage;
 This package is stored in subdirectory named firstPackage.secondPackage.
 A java package can contain more than one class definitions that can be
declared as public.
 Only one of the classes may be declared public and that class name with
.java extension is the source file name.
Default Package:
• If a source file does not begin with the package statement, the classes
contained in the source file reside in the default package
• The java compiler automatically looks in the default package to find classes

Finding Packages:
1. By default, java runtime system uses current directory as starting
point and search all the subdirectories for the package.
2. Specify a directory path using CLASSPATH environmental variable

ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes,
variables, methods and constructor
Types of access-specifiers:
 Default - Visible to the package, the default.
 Private - Visible to the class only.
 Public - Visible to the world.
 Protected -Visible to the package and all subclasses.
Levels of Access Control:
public protected friendly (default) private

same class Yes Yes Yes Yes

Subclass in Yes Yes Yes No


the same
package
Other class Yes Yes Yes No
in the
same package
Subclass in Yes Yes No No
other
packages
Non- subclass Yes No No No
in other
package

INTERFACES
 An interface in java is a blueprint of a class. It has static constants and
abstract methods only.
 The interface in java is a mechanism to achieve fully abstraction. There
can be only abstract methods in the java interface not method body.
 It is used to achieve fully abstraction and multiple inheritances in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.

Use of Interface:
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritances.
 It can be used to achieve loose coupling.

Relationship between Classes and Interfaces


As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface
Interface Syntax:
interface interfaceName
{
Variables declaration; Method declaration;
}
interface - keyword.
interfacename - any valid java variable.

Simple Example of Java Interface


In this example, Printable interface have only one method, its implementation is
provided in the A class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}

Output: Hello

Multiple Inheritances in Java by Interface


If a class implements multiple interfaces, or an interface extends multiple
interfaces i.e. known as multiple inheritance.

Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:
Hello
Welcome

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy