0% found this document useful (0 votes)
4 views60 pages

Chapter 4

Uploaded by

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

Chapter 4

Uploaded by

ankitdb04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Inheritance Concept

Concept of inheritance

Single inheritance Multiple inheritance


Concept of inheritance

Single multi-level inheritance Class hierarchy


Inheritance in Java
• Inheritance is one of the cornerstone of object-oriented
programming because it allows the creation of hierarchical
classification.
Vehicle
• Using inheritance, one can create a general class that include some
common set of items.
CAR TRUCK
• This class then can be used to create more specific classes which
has all the items from the base class, in addition to some items of
its own.
Terms used in inheritance
• Superclass: A class that is inherited is called a superclass.
• Subclass: The class that does inheriting is called a subclass. Vehicle
• A subclass is a specialized version of a superclass
• It inherits all of the instance variables and methods defined by the
superclass and add its own, unique elements (i.e., variables and CAR TRUCK
methods)
• Reusability: It is a mechanism which facilitates you to reuse the data and
methods of the existing class when one create a new class. Wagon Fire
• One can use the same data and methods already defined in the previous
Truck
class.
Inheritance syntax
• The extends keyword is used to define a new class that derives from
an existing class. The meaning of "extends" is to increase the
functionality.

class <Subclass-name> extends <Superclass-name> {


//data and methods in this sub-class
}
Example of a simple Inheritance
class Point2D{
int x;
int y;
void display(){
2D Point System.out.println ("x="+x+"y="+y);
}
}

class Point3D extends Point3D{


int z;
void display(){
3D Point System.out.println("x="+x+"y="+y+"z="+z);
}
}
Example of a simple Inheritance

class simpleSingleInheritance{
2D Point public static void main(String arge[]){
Point2D new P1();
Point3D new P2();
P1.x = 10;
P1.y = 20;
System.out.println("Point2D P1 is" + P1.display());
// Initializing Point3D
P2.x = 5;
P2.y = 6;
P3.z = 15;
3D Point System.out.println("Point3D P2 is" + P2.display());
}
}
Types of Inheritances
Inheritance types
Single inheritance Multiple single inheritance Multilevel single inheritance

Hybrid inheritance
Multiple inheritance
Inheritance types
Single inheritance Multiple single inheritance Multilevel single inheritance

Hybrid inheritance
Multiple inheritance
Single inheritance : An example
• name
• dob
Person • mobileNo
• readData()
• printData()

• empNo
• institution
• salaryHistory[]
• qualif[]
• organization
• rollNo Student Employee • designation
• marks[]
• doj
• printBioData()
• printSalary()
Single Inheritance in Java
Single Inheritance : Person class
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){
name = n;
dob = d;
mobileNo = m;
}
void printData(){
System.out.println("Name : "+ name);
dob.printDate();
System.out.println("Mobile : "+ mobileNo);
}
}
Single inheritance : Student class
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){ class Student extends Person{
name = n;
String institution;
dob = d;
mobileNo = m; int[] qualif = new int[20];
} int rollNo;
void printData(){ int[] marks = new int[5];
System.out.println("Name : "+ name);
dob.printDate(); void printBioData(){
System.out.println("Mobile : "+ mobileNo); printData();
} System.out.println("Institution : "+ institution);
}
System.out.println("Roll : "+ rollNo);
for(int q=0; q<qualif.length;q++){
System.out.println(“Marks "+q+": "+ qualif[q]);
}
for(int m=0; m<marks.length;m++){
System.out.print(“Result "+m+": "+marks[m]);
}
}
}
Single Inheritance – employee
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){
name = n;
dob = d;
mobileNo = m;
} class Employee extends Person{
void printData(){ int empNo;
System.out.println("Name : "+ name); int[] salaryHistory = new int[12];
dob.printDate(); String organization;
System.out.println("Mobile : "+ mobileNo); String designation;
} Date doj;
}
void printSalary(){
for(int s=0; s<salaryHistory.length;s++){
System.out.println("Salary "+s+": "+salaryHistory[s]);
}
}
}
Single Inheritance : An example

class inheritanceDemo1{
public static void main(String args[]){
Person p = new Person();
//Code with the objects p…
Student s = new Student [100];
//Code with the objects s…
Employee e = new Employee[50];
//Code with the objects e…

}
}
Multilevel inheritance : An example
Geo Object

1D Object 2D Object 3D Object

Point Straight Line Polygon Curve Sphere Cone Cylinder

Triangle Quadrilateral

Right Angled Isosceles Equilateral Rectangle Parallelogram


Method Overriding
Method overriding concept
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

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).
Method overriding : An example
class Point2D{
int x; class Point3D extends Point3D{
int y; int z;
Point2D(int a, int b){ Point3D(int c){
x = a; z = c;
y = b; }
} void display(){
void display(){ System.out.println("x="+x+"y="+y+"z="+z);
System.out.println("x = "+x+"y = "+y); }
} }
}

class MethodOverridingTest{
public static void main(String args[]){
Point2D p = new Point2D(3.0, -4.0);
p.display(); // Refers to the method in Point2D

Point3D q = new Point3D(0.0);


q.display(); // Refers to the method in Point3D

Point2D x =(Point2D) q; // Cast q to an instance of class Point2D


x.display();
}
}
Note

A sub class object can reference a super class variable or method if it is not
overridden.

A super class object cannot reference a variable or method which is explicit to


the sub class object.
super Keyword
super Keyword concept in Java

The super keyword in Java is a reference variable


which is used to refer immediate parent class members.

Whenever you create an instance of a sub class, an


instance of its parent class is created implicitly, which is
referred by super keyword.
super : Referring parent class instance variable
class Animal{
String color="white";
}
class Dog extends Animal{
String color = "black"; Animal and Dog both classes have a common
void printColor(){
System.out.println(color); property color. If you print the color property,
System.out.println(super.color); it will print the color of the current class by
}
} default. To access the parent property, you
class TestSuper1{ should use super keyword.
public static void main(String args[]){
Dog d = new Dog();
d.printColor();
}
}
super : Invoking parent class method
class Animal{ Animal and Dog both the classes have
void eat(){System.out.println("eating...");}
} eat() method. If you call eat() method
class Dog extends Animal{ from Dog class, it will call the eat()
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");} method of Dog class by default because
void work(){ priority is given to local.
super.eat();
bark();
eat();} To call the parent class method, you need to
}
class TestSuper2{
use super keyword.
public static void main(String args[]){
Dog d = new Dog();
d.work();
}
}
super : Invoking parent class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created"); The super keyword can also be
} used to invoke the overloaded
}
parent class constructor, if
class TestSuper3{ arguments are there, then they
public static void main(String args[]){
Dog d = new Dog(); should be specified accordingly.
}
}
super : Invoking parent class constructor
class Point2D{
double x, y;
Point2D(){x = 0.0; y = 0.0} //Default initialization
Point2D(double x, double y){thix.x = x; this.y = y;} If there is a number of
}
class Point3D extends Point2D{
overloading constructors
double z; in the super class, then
Point3D(){super(); z = 0.0} //Default initialization you have to define the
Point3D(double x, double y, double z){
super(x, y);
super constructors
this.z = z; } matching with each
} constructor.
class TestSuper4{
public static void main(String args[]){
Point3D p = new Point3D(2.0, 3.0, 4.0);
}
}
Abstract class in Java
Abstract concept

• Abstraction is a process of hiding the implementation details and


showing only functionality to the user.

• Abstraction lets you focus on what the object does instead of how
it does it.

• 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 (i.e., method with the body only without its definition).
Abstract concept
Points to remember

• An abstract class must be declared with an abstract keyword.


• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the sub class not to change the body of the
method.
Abstract class in Java : Example

abstract class Bike{


abstract void run();
Here, Bike is an abstract class that
} contains only one abstract method run().
class Honda extends Bike{
void run(){ Its implementation is provided by the
System.out.println(“Running safely"); Honda class.
}

public static void main(String args[]){ Note:


Bike obj = new Honda();
obj.run(); An abstract method should be defined in it
} sub class.
}
final Keyword in Java
final keyword concept
The final keyword in Java is used to restrict the access of an
item from its super class to a sub class. The Java final
keyword can be used in many context.
• Variable : a variable cannot be accessed in sub class
• Method : a method cannot called from a sub class object
• Class : a class cannot be sub classed.

Note:
If you make any class as final, you cannot extend it.
Final class in inheritance : An Example

final class Bike{}

class Honda1 extends Bike{


void run(){
System.out.println(“Running safely with 100kmph");
} Extending a class which is declared as final
will cause compile time error.
public static void main(String args[]){
Honda1 honda = new Honda1();
honda.run();
}
}
Question to think…

• Can we inherit a class from other class which is


defined in other package?
• How information access can be restricted in a class?
Access Modifiers in Java
Concept of access modifiers
The access modifiers in Java specify accessibility (scope) of a data member,
method, constructor or class.

Access modifier

Type of access modifiers :

Visible to the Visible anywhere Visible to the Visible to the


same package inherited classes class only
Access levels of modifiers
Access levels

Modifier Class Package Sub class Everywhere

Public ✔ ✔ ✔ ✔
Protected ✔ ✔ ✔ ✘
Default ✔ ✔ ✘ ✘
Private ✔ ✘ ✘ ✘
Default access modifier

If you don't use any modifier, it is treated


as default by default.

The default modifier is accessible only


within a package.
Default access modifier : An Example
//Save this program as A.java in a sub-directory “pack1” Here, two classes are with default
class A { access modifier. If they reside in
void msg(){System.out.println(“Hi! I am in Class A");
} two different directories, then the
}
class A is not accessible to
class B and vice-versa.
/* Save this program as B.java in another sub-directory
“pack2” */ However, if they reside in the same
class B{ directory, then there will be no
public static void main(String args[]){
A obj = new A(); //Compile Time Error error!
obj.msg(); //Compile Time Error
}
}
Default access modifier : Another example

//Save this program as A.java


package pack1; // It is a sub-directory “pack1”
class A { Suppose, there are two packages, say
void msg(){System.out.println(“Hi! I am in Class A");}
}
pack 1 and pack2.

Here, class A and class B are


//Save this program as B.java declared as default and we are
package pack2; //It is in a sub-directory “pack2”
import pack1.*; /* Import all class files in pack1 */
accessing the class A from outside
its package, since class A is
class B{ default, so it cannot be accessed
public static void main(String args[]){
A obj = new A(); //Compile Time Error from any outside package.
obj.msg(); //Compile Time Error
}
}
Default access modifier : An Example
//Save this program as A.java in a directory, say temp.

class A {
void msg(){System.out.println(“Hi! I am in Class A");
}
} Here, two classes are with default access
modifier, and thy are residing in the same
directory (or may be in the same file).
/* Save this program as B.java in the same directory */ Hence, in this case, the class A is
class B{ accessible to class B and vice-versa.
public static void main(String args[]){
A obj = new A(); //Okay. It is accessible.
obj.msg(); //It is also accessible.
}
}
Public access modifier

The public access modifier is accessible


everywhere.

It has the widest scope among all other


modifiers.
public access modifier : An Example
//Save as A.java in a sub-directory say pack1
package pack1; The class A in package pack1 is
public class A{
public void msg(){ public, so this class can be accessed
System.out.println(“Class A: Hello Java!");
} from any class outside to this package,
} for example, in this case, from class
B in pack2 .
//Save as B.java in another sub-directory say pack2
package pack2;
import pack1.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
public access modifier : An example
public class A{
public int data = 40;
public void msg(){ We have created two classes class A and
System.out.println(“Class A: Hello Java!");
} class B. The class A contains public
} data member and public method and are
public class B{
accessible to class B.
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);
Note:
//OK : data is public It does not matter whether the class A and
obj.msg(); //OK: msg is public class B belong to the same directory or in
}
} the same program file.
Public access modifier : Another example
//Save this program as A.java
package pack1; // It is a sub-directory “pack1”

public class A {
void msg(){System.out.println(“Hi! I am in Class A");}
}

//Save this program as B.java When a class is public, all its


package pack2; // It is another sub-directory “pack2”
import pack1.*; /* Import all classes in pack1 here member with default access specifier
are also public.
class B{
public static void main(String args[]){
A obj = new A(); //Okay program!
obj.msg(); //This is now public
}
}
Private access modifier

The private access modifier is


accessible only within the class.
Private access modifier : An example

public class A{
private int data = 40;
public void msg(){
System.out.println(“Class A: Hello Java!");
}
}

public class B{
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);
//Compile Time Error : data is private
obj.msg(); //OK : msg is public
}
}
Private access modifier : An example

private class A{
int data = 40;
void msg(){
System.out.println(“Class A: Hello Java!"); When a class is private, all its
}
} member with default access specifier
are also private.
public class B{
public static void main(String args[]){
A obj = new A(); //Error : Class A is public How, if a member in a public class is
System.out.println(obj.data);
//Compile Time Error : data is private declared as public or protected?
obj.msg(); //Error : msg is private
}
}
Think about this…

public class A{
private int data = 40;
public void msg(){
System.out.println("Hello Java!“ + data);
}
}

public class B{
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);//Compile Time Error : data is private
obj.msg(); //Calls msg() method of class A, which in turns private data : Error!
}
}
private constructor : An example
public class A{
private A(){
//private constructor
}
void msg(){ If you make any class constructor
}
System.out.println(“Class A: Hello Java!"); private, you can not create an
} instance of that class from outside the
public class Simple{ class.
public static void main(String args[]){
A obj = new A(); //Compile Time Error!
}
}
Protected access modifier

The protected access modifier is accessible within a


package or from outside a package but through
inheritance only.

The protected access modifier can be applied on the data


member, method and constructor. It can't be applied on
the class.
Protected access modifier : An Example

public class A{
protected int i = 555; Here, the protected data i is accessible to
void msg(){ any methods in the same class. Alos, it is
System.out.println(“Class A: Hello Java!“ + i);
}
accessible to any of its sub class.
}
Here, class A is accessible to class B
as it is declared public; however, any
class B { method in the class B (even they are in
public static void main(String args[]){
A obj = new A(); the same file or package) cannot access
obj.msg(); // Error: Compilation error protected data of class A directly or
}
} indirectly.
Protected access modifier : An Example
public class A{
public int i = 555; Here, the msg() method of the
protected void msg(){ class A is declared as protected,
System.out.println("Hello Java! + i");
} and hence, it can be accessed from
}
outside the class only through
inheritance.
class B extends A{
public static void main(String args[]){
B obj = new B(); What will happen if i is made private
obj.msg();
} in class A?
}
Protected access modifier : Another Example
//Save as A.java in a sub directory pack1
package pack1;

public class A{
protected void msg(){
We have created the two packages pack1
System.out.println(“Class A: Hello Java!"); and pack2.
}
}
The class A of pack1 package is
//Save as B.java in another sub-directory pack2 public, so can be accessed from outside
package pack2; the package. The method msg() of the
import pack1.*;
class A is declared as protected, so it
class B extends A{ can be accessed from outside the class
public static void main(String args[]){
B obj = new B();
through inheritance.
obj.msg();
}
}
Java access modifiers with method overriding
public class A{
protected void msg(){ If you are overriding any method, overridden
System.out.println(“Class A: Hello Java!"); method (i.e. declared in sub class) must not be
}
} more restrictive.
public class Simple extends A{
void msg(){ The default modifier is more restrictive than
System.out.println(“Class B: Welcome!"); protected. That is why, there is compile time
//Compile Time Error
} error.
public static void main(String args[]){ What will happen if the msg() in class
Simple obj = new Simple();
obj.msg(); Simple is declared as public or
} protected?
}
Questions to think…

• How a package can be built ?


• Is it possible that two classes having
the same name but in two different
packages are to be used in another
class outside the packages?

You might also like