0% found this document useful (0 votes)
2 views17 pages

Module 3 Part2

Uploaded by

Satti Mounica
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Module 3 Part2

Uploaded by

Satti Mounica
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INHERITANCE

Part-2
It is the mechanism in java by which one class(child class) is allowed to inherit the
features(fields and methods) of another class(parent class).
 Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
 Uses of Inheritance

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

Example:

Class parent
{
Void method1()
{
[Link](“hello parent”);
}
}
o Sub Class/Child Class: Subclass is a class which inherits the other class using extend
keyword. It is also called a derived class, extended class, or child class.

Class child extends parent


{
Void method2()
{
[Link](“hello child”);
}
}
Member access or VISIBILITY CONTROL
It is possible to inherit all the members of a class by a subclass using the
keyword extends. The variables and methods of a class are visible everywhere in the
program. However, it may be necessary in some situations where we may want them to be
not accessible outside. We can achieve this in Java by applying visibility modifiers to
instance variables and methods. The visibility modifiers are also known as access
modifiers. Access modifiers determine the accessibility of the members of a class.
Java provides the following visibility/access modifiers:
 Public
 Friendly/Package(default)
 Private
 Protected

They provide different levels of protection as described below.


Public Access: Any variable or method is visible to the entire class in which it is defined.
But, to make a member accessible outside with objects, we simply declare the variable or
method as public. A variable or method declared as public has the widest possible visibility
and accessible everywhere.
Friendly Access (Default): When no access modifier is specified, the member defaults to a
limited version of public accessibility known as "friendly" level of access. The difference
between the "public" access and the "friendly" access is that the public modifier makes fields
visible in all classes, regardless of their packages while the friendly access makes fields
visible only in the same package, but not in other packages.
Protected Access: The visibility level of a "protected" field lies in between the public access
and friendly access. That is, the protected modifier makes the fields visible not only to all
classes and subclasses in the same package but also to subclasses in other packages
Private Access: Private fields have the highest degree of protection. They are accessible only
with their own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. In the case of overriding public methods cannot be redefined as private type.
Private protected Access: A field can be declared with two keywords Private and Protected
together. This gives a visibility level in between the "protected" access and "private" access.
This modifier makes the fields visible in all subclasses regardless of what package they are
in. Remember, these fields are not accessible by other classes in the same package.
The following table summarizes the visibility provided by various access modifiers.
Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Types of inheritance:
SINGLE INHERITANCE
When a class extends another one class only then we call it a single inheritance. The below
flow diagram shows that class B extends only one class which is A. Here A is a Super
class of B and B would be a Sub class of A.
Example Program on Single Inheritance
class A
{ public void methodA()
{ [Link]("Base class method");
}
}
class B extends A
{ public void methodB()
{ [Link]("Child class method");
}
}
class single
{ public static void main(String args[])
{ B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
OUTPUT:
Base class method
Child class method

SUBCLASS CONSTRUCTOR
A subclass constructor is used to construct the instance variables of both the subclass and the
superclass. The subclass constructor uses the keyword super to invoke the constructor method
of the superclass. The call to the superclass constructor must appear as the first statement
within the subclass constructor and the parameters in the super call must match the order and
type of the instance variable declared in the superclass.
Example program1
class parent
{
parent()
{
[Link]("p1");
}
}
class child extends parent
{
child()
{
[Link]("p2");
}
}
class single {
public static void main(String[] args) {
child n=new child();
}
}
Output: p1p2
Example program2
class Room
{ int l,b;
Room(int x, int y)
{ l=x;b=y; }
int area()
{ return(l*b); }
}
class Bedroom extends Room //Inheriting Room
{ int h;
Bedroom(int x,int y, int z)
{ super(x,y); // Pass values to superclass
h = z;
}
int volume()
{ return(l*b*h); }
}
class subclasscons
{ public static void main(String args[])
{ Bedroom room1=new Bedroom(10,15,20);
int a=[Link](); //superclass method
int v=[Link](); //subclass method
[Link]("Area= "+a);
[Link]("Volume="+v);
}
}
OUTPUT: Area=150
Volume=3000

SUPER KEYWORD

The super keyword in java is a reference variable that is used to refer immediate parent class
object.

Whenever an instance of subclass is created, an instance of parent class is created implicitly


i.e. referred by super reference variable.

Usage of java super Keyword


1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.

1. // super keyword in subclass is used to refer immediate parent class instance


variable.
class Vehicle{
int speed=50;
}
class Bike4 extends Vehicle
{ int speed=100;
void display()
{ [Link]([Link]);//will print speed of Vehicle now
[Link](speed);//will print speed of Bike4 now
}
public static void main(String args[])
{ Bike4 b=new Bike4();
[Link]();
}
}
OUTPUT : 50
100

2. super is used to invoke immediate parent class method.

class parent
{
parent()
{
[Link]("p1");
}
void m1()
{
[Link]("parent m1");
}
}
class child extends parent
{
child()
{
[Link]("p2");
}
void m1()
{
[Link]("child m1");
}
void m2()
{
m1();
super.m1();
}
}
class single {
public static void main(String[] args) {
child n=new child();
n.m2();
}
}
Output: p1
p2
child m1
parent m1

4. super() is used to invoke immediate parent class constructor.

class parent
{
parent()
{
[Link]("p1");
}

}
class child extends parent
{
child()
{
super();
[Link]("p2");
}

}
class single {
public static void main(String[] args) {
child n=new child();

}
}
Output:
p1
p2
MULTILEVEL INHERITANCE
Multilevel inheritance refers to a mechanism in Object Oriented technology where one can
inherit from a derived class, thereby making this derived class the base class for the new
class. As you can see in below flow diagram C is subclass or child class of B and B is a child
class of A.
Example Program on Multilevel Inheritance
class X
{ public void methodX()
{ [Link]("Class X method"); }
}
class Y extends X
{ public void methodY()
{ [Link]("class Y method"); }
}
class Z extends Y
{ public void methodZ()
{ [Link]("class Z method"); }
}
class multilevel
{
public static void main(String args[])
{ Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
OUTPUT :
Class X method
Class Y method
Class Z method

HIERARCHICAL INHERITANCE
In this type of inheritance one class is inherited by many sub classes.
Example Program on Hierarchical Inheritance
class A
{ int a=10; }
class B extends A
{ int b=30;
void display()
{ [Link]("The values are:"+a+" "+b); }
}
class C extends A
{ int c=40;
void show()
{ [Link]("The values are:"+a+" "+c); }
}
class hierarchicaldemo
{ public static void main(String args[])
{ B obj1=new B();
[Link]();
C obj2=new C();
[Link]();
}
}
OUTPUT:
The values are:10 30
The values are:10 40

Constructor execution hierarchy:


class X
{ X()
{
[Link]("x");
}
public void methodX()
{ [Link]("Class X method"); }
}
class Y extends X
{
Y()
{
[Link]("y");
}public void methodY()
{ [Link]("class Y method"); }
}
class Z extends Y
{
Z()
{
[Link]("z");
}public void methodZ()
{ [Link]("class Z method"); }
}
class multilevel
{
public static void main(String args[])
{ Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
Output:
x
y
z
Class X method
class Y methodclass Z method

Super class reference and subclass objects:


In Java, all non-static methods are based on the runtime type of the underlying object rather
than the type of the reference that points to that object. Therefore, it doesn’t matter which
type you use in the declaration of the object, the behavior will be the same.
How to Refer a subclass object
There are two approaches to refer a subclass object. Both have some
advantages/disadvantages over the other. The declaration affect is seen on methods that are
visible at compile-time.
1. First approach (Referencing using Superclass reference): A reference variable of a
superclass can be used to a refer any subclass object derived from that superclass. If the
methods are present in SuperClass, but overridden by SubClass, it will be the
overridden method that will be executed.
2. Second approach (Referencing using subclass reference) : A subclass reference can
be used to refer its object.
Example:
class Parent {
public void parentPrint() {
[Link]("parent print called");
}
public static void staticMethod() {
[Link]("parent static method called");
}
}
class SubclassReference extends Parent {
public void parentPrint() {
[Link]("child print called");
}
public static void staticMethod() {
[Link]("child static method called");
}
public static void main(String[] args) {

Parent obj = new SubclassReference();


[Link](); //method of subclass would execute as subclass object at
runtime.
[Link](); //method of superclass would execute as reference of
superclass.
Parent obj1 = new Parent();
[Link](); //method of superclass would execute as superclass object at
runtime.
[Link](); //method of superclass would execute as reference of
superclass.
SubclassReference obj3 = new SubclassReference();
[Link](); //method of subclass would execute as subclass object at
runtime.
[Link](); //method of subclass would execute as reference of subclass.
}
}
Output: child print called
parent static method called
parent print called
parent static method called
child print called
child static method called

Method Overriding:

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.

Example:
Design a vehicle class hierarchy in Java, and develop a program to demonstrate
Polymorphism.
import [Link].*;
class Vehicle
{ String regno;
int model;
Vehicle(String r, int m)
{ regno=r;
model=m;
}
void display()
{ [Link]("registration no:"+regno);
[Link]("model no:"+model);
}
}
class Twowheeler extends Vehicle
{ int noofwheel;
Twowheeler(String r,int m,int n)
{ super(r,m);
noofwheel=n;
}
void display()
{ [Link]("Two wheeler tvs");
[Link]();
[Link]("no of wheel" +noofwheel);
}
}

class Threewheeler extends Vehicle


{ int noofleaf;
Threewheeler(String r,int m,int n)
{ super(r,m);
noofleaf=n;
}
void display()
{ [Link]("three wheeler auto");
[Link]();
[Link]("no of leaf" +noofleaf);
}
}

class Fourwheeler extends Vehicle


{ int noofleaf;
Fourwheeler(String r,int m,int n)
{ super(r,m);
noofleaf=n;
}
void display()
{ [Link]("four wheeler car");
[Link]();
[Link]("no of leaf" +noofleaf);
}
}

public class Vehicledemo


{ public static void main(String arg[])
{ Twowheeler t1;
Threewheeler th1;
Fourwheeler f1;
t1=new Twowheeler("TN74 12345", 1,2);
th1=new Threewheeler("TN74 54321", 4,3);
f1=new Fourwheeler("TN34 45677",5,4);
[Link]();
[Link]();
[Link]();
}
}
OUTPUT :
Two wheeler tvs
registration no:TN74 12345
model no:1
no of wheel2
three wheeler auto
registration no:TN74 54321
model no:4
no of leaf3
four wheeler car
registration no:TN34 45677
model no:5
no of leaf4

ABSTRACT METHODS AND CLASSES


An abstract class is a class that is declared abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces,


and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}

When an abstract class is subclassed, the subclass usually provides implementations for all of
the abstract methods in its parent class. However, if it does not, then the subclass must also be
declared abstract.
Example of Abstract class and Abstract Methods
abstract class Bike
{ Bike()
{ [Link]("bike is created"); }
abstract void run();
void changeGear()
{ [Link]("gear changed"); }
}
class Honda extends Bike
{ void run()
{ [Link]("running safely.."); }
}
class abstractdemo1
{ public static void main(String args[])
{ Honda obj = new Honda();
[Link]();
[Link]();
}
}
OUTPUT:
bike is created
running safely..
gear changed

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in
many contexts. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that has no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only.

1) Java final variable


A variable declared as final, cannot change its value(It will be constant).

Example of final variable

There is a final variable speedlimit, trying to change the value of this variable is not possible
because final variable once assigned a value can never be changed.

class FinalVariable
{ final int speedlimit=90;//final variable
void run()
{ speedlimit=400; }
}
class Bike1 extends FinalVariable
{ int speedlimit=80;
public static void main(String args[])
{ Bike1 obj=new Bike1();
[Link]();
[Link]("obj"+ [Link]);
}
}

OUTPUT:
[Link]: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error

2) Java final method

Final method is inherited but cannot be overridden.

class finalmethod
{ final void demo()
{ [Link]("finalmethod Class Method"); }
}

class finalmethoddemo extends finalmethod


{ void demo()
{ [Link]("finalmethoddemo Class Method"); }
public static void main(String args[])
{ finalmethoddemo obj= new finalmethoddemo();
[Link]();
}
}
OUTPUT:
[Link]: error: demo() in finalmethoddemo cannot override demo()
in finalmethod
void demo()
^
overridden method is final
1 error
3) Java final class

Any class declared as final, cannot be extended.

final class XYZ


{ void demo()
{ [Link]("My Method"); }
}
class finalclassdemo extends XYZ
{ public static void main(String args[])
{ finalclassdemo obj= new finalclassdemo();
[Link]();
}
}
OUTPUT:
[Link]: error: cannot inherit from final XYZ
class finalclassdemo extends XYZ
^
1 error

You might also like