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

Inheritance notes

Inheritance in Java allows one class to inherit properties from another, creating a hierarchical relationship that promotes code reusability. There are various types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, each serving different structural needs. Access modifiers regulate the visibility of class members, with specific rules about what is inherited, particularly regarding private and protected members.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Inheritance notes

Inheritance in Java allows one class to inherit properties from another, creating a hierarchical relationship that promotes code reusability. There are various types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, each serving different structural needs. Access modifiers regulate the visibility of class members, with specific rules about what is inherited, particularly regarding private and protected members.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Inheritance

It is a process by which one class can inherit the property of another class.
It represents hierarchical relationship. This hierarchical relationship representation
ensures closeness to the real-world models. It is used to build new classes from
existing classes.

Suppose new class B is derived from class A, then class A is called the base class and
class B is called the derived class. The relation between the base class and derived
class is referred to as a derivation of inheritance hierarchy.

Superclass or base class: is the class that is inherited.


Derived or subclass: is the class that is derived from the super class(inheriting class).

Need for Inheritance


• Capability to express the hierarchical relationship: using inheritance close to real-
world models.
• Reusability of code: a new class can be derived from the existing class(base class)
and additional features can be added to it.
• Transitive nature of inheritance: Once a class A is defined then class B can be
derived from it. So, A is the base class and B is the derived class. Now, class B can
act as the base class for another class C. So, it can be transitive in nature.
What is not possible in java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can
only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not
inherited by subclasses in other packages, as these members are only
accessible by their simple names in subclasses within the same package as
the superclass.
3. Since constructors is an initializer blocks they are not members of a class
and are not inherited by a subclass.
4. A subclass can extend only one superclass.
Types of Inheritance *
1. Single inheritance: when the subclass is inherited from only one base class, it is
know as single inheritance.
2. Multiple inheritance: when a subclass inherits from multiple base classes it is
called multiple inheritance.
3. Hierarchical inheritance: when many subclasses inherit from a single base class,
it is called hierarchical inheritance.
4. Multilevel inheritance: the transitive nature of inheritance is reflected in
multilevel inheritance.
5. Hybrid inheritance: it is a combination of the above inheritance types.

Member Type Inside own Inside Inside Inside non- Inside non-
Class subclass in subclass in subclass in subclass in
the same other the same other
Package Package package package
public Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes No
Default(friendly) Yes Yes Yes No No
Private Yes No No No No

Access Modifiers
The access to classes, constructors, methods and fields are regulated using access
modifiers. Ie. a class can control what information or data can be accessible by other
classes. Java provides a number of access modifiers to help you set the level of access
you want for classes as well as the fields, methods and constructors in your classes. A
member has package or default accessibility when no accessibility modifiers is
specified.
Access Modifiers can be:
1. private
2. protected
3. default
4. public

public access modifier


Data members, methods and constructors declared public (least restrictive)within a
public class are visible to any class in the Java program, whether these classes are in the
same package or in another package.

Private access modifier


Data members, methods and constructors declared private (maximum restrictive)with a
private class are visible in the class declared.
Protected Access modifier
The protected fields or methods cannot be used for classes and interface. Data
members, methods and constructors declared as protected (maximum restrictive) can
be visible in the super class and in the sub class of same package or other package.

Default Access modifier


Java provides a default specifier which is used when no access modifier is present. Any
class, field, method or constructor that has no access modifier is accesses only in the
classes within the package.

Example 1
Public data members are inherited
class base
{ int i,j;
base()
{ i=30;
j=40;
}
}
--------------------
class Derived extends base
{ int c;
Derived()
{ c=70;
}
void Display1()
{ System.out.println("i="+i+" j="+j+" c="+c);
} }
-----------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived();
d.Display1();
}}
Output
i=30 j=40 c=70
======================================================
===
Example 2
//Protected data members are inherited
class base
{ protected int i,j;
base()
{ i=30;
j=40;
}
}
-------------------------
class Derived extends base
{ int c;
Derived()
{ c=70;
}
void Display1()
{ System.out.println("i="+i+" j="+j+" c="+c);
}
}
--------------------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived();
d.Display1();
}}
Output
i=30 j=40 c=70

======================================================
======
Example 3
// Private data members are inherited
class base
{ private int i,j;
base()
{ i=30;
j=40;
}
}
--------------------
class Derived extends base
{ int c;
Derived()
{ c=70;
}
void Display1()
{ System.out.println("i="+i+" j="+j+" c="+c);
}
}
---------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived();
d.Display1();
}}

Note: The above program gives the following compilation error as private data
members cannot be inherited
C:\Program Files\Xinox Software\JCreator LE\MyProjects\MyPack\circle.java:15: i has
private access in base
{ System.out.println("i="+i+" j="+j+" c="+c);
^
C:\Program Files\Xinox Software\JCreator LE\MyProjects\MyPack\circle.java:15: j has
private access in base
{ System.out.println("i="+i+" j="+j+" c="+c);
^
2 errors
===========================================
Example 3
//As private members cannot be inherited they can be printed through a public
method.
class base
{ private int i,j;
base()
{ i=30;
j=40;
}
void Display()
{ System.out.print("i="+i+" j="+j);
}
}
--------------------------
class Derived extends base
{ int c;
Derived()
{ c=70;
}
void Display()
{ super.Display();
System.out.println("c="+c);
}
}
-------------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived();
d.Display();
}}
Output
i=30 j=40 c=70

============================================
Getter / Accessor Methods
As private members cannot be inherited in derived class their values can be accessed
through getter/Accessor method. So, the method that only returns the value of private
data members is called Getter/Accessor methods.
class base
{ private int i,j;
base()
{ i=30;
j=40;
}
int getI()
{ return i;
}
int getJ()
{ return j;
}
}
----------------
class Derived extends base
{ int c;
Derived()
{ c=70;
}
void Display1()
{ int s;
s=getI()+getJ()+c;
System.out.println("s="+s);
}
}
------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived();
d.Display1();
}}
Output
s=140
============================================
Setter / Mutator Methods
Private data members values cannot be altered in the derived class. They can be altered
through setter or mutator methods. So, the method with parameter (parameterized
method) changes the value of private data member. Such methods are called
Getter/Accessor methods.

class base
{ private int i,j;
base()
{ i=30;
j=40;
}
int getI()
{ return i;
}
int getJ()
{ return j;
}
void setI(int i1)
{ i=i1;
}
void setJ(int j1)
{ j=j1;
}
}
//----------------
class Derived extends base
{ int c;
Derived()
{ c=70;
}
void Display1()
{ int s;
s=getI()+getJ()+c;
System.out.println("s="+s);
setI(100);
setJ(200);
s=getI()+getJ()+c;
System.out.println("s="+s);

}
}
//------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived();
d.Display1();
}}

============================================
Super
If a super class has parameterized constructor then it is compulsory for the subclass to
have parameterized constructor so, that the values from the subclass can be passed to
the super class. In Java, the keyword super(..) with parameters is used to pass
parameter from the subclass to super class.
Note: super should be the first statement in the derived class constructor.
Example of keyword super
class base
{ private int i,j;
base(int i1,int j1)
{ i=i1;
j=j1;
}
int getI()
{ return i;
}
int getJ()
{ return j;
}
}
--------------
class Derived extends base
{ int c;
Derived(int i1,int j1,int c1)
{super(i1,j1);
c=c1;
}
void Display1()
{ int s;
s=getI()+getJ()+c;
System.out.println("s="+s);
}
}
--------------------
class Inher
{ public static void main(String args[])
{ Derived d = new Derived(40,50,60);
d.Display1();
}}
Output
s=150

Method Overloading
When a class contains more than one method then all the methods should contain the
same name but different parameters, then it is called method overloading. For
example the following are the overloaded method in the Math class.
• long Math.max(long , long );
• int Math.max(int, int)
• double Math.max(double, double)
• float Math.max(float, float)

Method Overriding
In a class hierarchy, when a method in subclass has the same name and signature as
the method in its super class, the method in subclass is said to override the methods in
the super class. When an overridden method is called from within a subclass, it will
refer to the version of that method defined in the subclass.
Example of Method Overriding
class base
{ private int i,j;
base(int i1,int j1)
{ i=i1;
j=j1;
}
void Display()
{
System.out.println("i= "+i+" j= "+j);
}
}
-------------------------------
class Derived extends base
{ int c;
Derived(int i1,int j1,int c1)
{super(i1,j1);
c=c1;
}
void Display()
{
System.out.println("c="+c);
}
}
class Inher
{ public static void main(String args[])
{ Derived d = new Derived(40,50,60);
d.Display();
}}
Output
C=60

ABSTRACT

A class is declared abstract using the keyword abstract. It can have zero or more abstract
and non-abstract methods. We need to extend the abstract class and implement its
methods. It cannot be instantiated.

An Abstract class is the one that simply represents a concepts and whose object cannot be
created. It is created using the keyword Abstract.

Syntax for abstract class:

1. abstract class class_name {


2. //abstract or non-abstract methods
3. }

Note: An abstract class may or may not contain abstract methods.

Abstract Method

A method declared using the abstract keyword within an abstract class and does not have a
definition (implementation) is called an abstract method.

When we need just the method declaration in a super class, it can be achieved by declaring
the methods as abstracts.

Abstract method is also called subclass responsibility as it doesn't have the implementation
in the super class. Therefore, a subclass must override it to provide the method definition.

Syntax for abstract method:

1. abstract return_type method_name( [ argument-list ] );

Here, the abstract method doesn't have a method body. It may have zero or more
arguments.

Points to Remember

Following points are the important rules for abstract method in Java:

o An abstract method do not have a body (implementation), they just have a method
signature (declaration). The class which extends the abstract class implements the
abstract methods.
o If a non-abstract (concrete) class extends an abstract class, then the class must
implement all the abstract methods of that abstract class.
o As the abstract methods just have the signature, it needs to have semicolon (;) at the
end.
o If a class contains abstract method it needs to be abstract and vice versa is not true.

Don'ts

o An abstract keyword cannot be used with variables and constructors.


o If a class is abstract, it cannot be instantiated.
o If a method is abstract, it doesn't contain the body.
o We cannot use the abstract keyword with the final.
o We cannot declare abstract methods as private.
o We cannot declare abstract methods as static.
o An abstract method can't be synchronized.

Do's

o An abstract keyword can only be used with class and method.


o An abstract class can contain constructors and static methods.
o If a class extends the abstract class, it must also implement at least one

of the abstract method.


Example of Abstract Method in Java

Example 1:

In the following example, we will learn how abstraction is achieved using abstract classes and
abstract methods.

AbstractMethodEx1.java

1. // abstract class
2. abstract class Multiply {
// abstract methods
3. // sub class must implement these methods
4. public abstract int MultiplyTwo (int n1, int n2);
5. public abstract int MultiplyThree (int n1, int n2, int n3);
6.
7. // regular method with body
8. public void show() {
9. System.out.println ("Method of abstract class Multiply");
10. }
11. }
12. ----------------------------------------------------------------------
13. // Regular class extends abstract class
14. class AbstractMethodEx1 extends Multiply {
15.
16. // if the abstract methods are not implemented, compiler will give an error
17. public int MultiplyTwo (int num1, int num2) {
18. return num1 * num2;
19. }
20. public int MultiplyThree (int num1, int num2, int num3) {
21. return num1 * num2 * num3;
22. }
23.
24. // main method
25. public static void main (String args[]) {
26. AbstractMethodEx1 obj = new AbstractMethodEx1();
27. System.out.println ("Multiplication of 2 numbers: " + obj.MultiplyTwo (10, 50));
28. System.out.println ("Multiplication of 3 numbers: " + obj.MultiplyThree (5, 8, 10
));
29. obj.show();
30. }
31. }

Output:

Example 3 on Abstract class and Abstract Method


abstract class Shape
{ String n;
double a;
public abstract void display();
}
//------------------
// class rectangle and circle which extends abstract class
class Circle extends Shape
{ double r;
Circle()
{ r=5.0;
n="Circle";
}
double calArea()
{ a=3.14*r*r;
return a;
}
public void display()
{ System.out.println("----------");
System.out.println(" Shape is ="+n);
System.out.println(" Radius is = "+r);
System.out.println(" Area is "+ calArea());
}
}
------------------------
class Rectangle extends Shape
{ double l,b;
Rectangle()
{ l=5.0; b=7.0;
n="Rectangle";
}
double calArea()
{ a=l*b;
return a;
}
public void display()
{ System.out.println("----------");
System.out.println(" Shape is ="+n);
System.out.println(" length is = "+l+"Breadth is"+b);
System.out.println(" Area is "+ calArea());
}
}
-----------------------------------
class abst
{ public static void main(String args[])
{ Circle C = new Circle();
Rectangle R = new Rectangle();
C.display();
R.display();
}}
Output
----------
Shape is =Circle
Radius is = 5.0
Area is 78.5
----------
Shape is =Rectangle
length is = 5.0Breadth is7.0
Area is 35.0

Interface
.
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

Interface defines a protocol of behavior. The aim of interfaces in java is to


dictate common behavior among objects from diverse classes.
A class that implements an interface adheres to the protocol defined by the interface
and has to implement all the methods declared in the interface.
Note: A class can implement as many interface but can extend only one class.
Notes on Interfaces:

• Interface methods do not have a body - the body is provided by the "implement"
class
• On implementation of an interface, you must override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor (as it cannot be used to create objects)

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why And When To Use Interfaces?

1) To achieve security - hide certain details and only show the important details of an
object (interface).

2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. Note: To implement multiple interfaces, separate
them with a comma (see example below).

Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.
The relationship between classes and interfaces

A class extends another class, an interface extends another interface, but a class
implements an interface.

class→ extends → class


class →implements → interface
interface→extends→interface

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank
interface.

File: TestInterface2.java

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Test it Now
Output:

ROI: 9.15

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple inheritance.

Question 11
An interfaces Student has been defined with the attributes and methods in it.
An interface Marks has been defined with the attributes and methods in it.
Define a class Result which uses the interfaces and calculates total and averages based
on the condition and prints the results.

Interface : Student
Data members : String name;
int admission number;
void Show() : To display all the details.
Interface : Marks
Data members : double me,mm, mc
void Show() : To display all the details.
--------------------------------------------------------------------------------------------
Create a sub-class with implements the above interface.
Class Name : Result
Data members : float me(English), mm(Maths), mp(Physics) mc(Computers)
float calTotal() : To find the total and return it.
float calAverage(): To find the average and return it.
String Result(): To print the result based on the following and return it

Average Result
>=80 Distinction
>=60 and <80 I Class
>=40 and <60 II Class
<40 Fail

void Show() : To display all the details of both the base class and the derived class
Admission No: -------- Name : ---------
English ------- Math --------- Physics -------- Computers ---------
Total -------- Average --------
Result --------

Example program on interface

public interface Student


{ int rollno = 100;
String name = "Roopa";
public void Display();
}
---------------------------------------
public interface Marks
{ double eng=66.8;
double mat = 78.4;
double com = 94.4;
double Total();
double Average();
}
--------------------------------------
class report implements Student, Marks
{ double tot,avg;
public double Total()
{ tot = mat + eng +com;
return tot;
}
public double Average()
{ avg = tot /3;
return avg;
}
public void Display()
{ System.out.println("Roll number :"+ rollno);
System.out.println("Name :"+ name);
System.out.println("English :"+ eng);
System.out.println("Maths :"+ mat);
System.out.println("Computer :"+ com);
System.out.println("Total :"+ Total());
System.out.println("Average :"+ Average());
}
}
--------------------------------------------
class Mmain
{ public static void main(String args[])
{ report R = new report();
R.Display();
}
}

/* ................ Example on interface ........ */

import java.io.*;
interface MyInterface1
{
public void Acc();
public double calculate();
public void Display();
}
-------------------------------------
interface MyInterface2
{
public void Repeat();
}
-------------------------------------------
public class circle implements MyInterface1, MyInterface2
{ double r;
Scanner sc = new Scanner(System.in);
circle()
{ r=0.0;
}
public void Acc()
{ try
{
System.out.println("Enter radius");
r=sc.nextDouble();
}
catch(Exception e)
{ System.out.println("Wrong Entry :");
}
}
public double calculate()
{ double a;
a = 3.14*r*r;
return a;
}
public void Repeat()
{ int c=1;
while(c<=3)
{
Acc();
Display();
c=c+1;
}
}
public void Display()
{
System.out.println("Area of circle "+ calculate() +" radius "+r);
}
public static void main(String args[])
{
circle C = new circle();
C.Repeat();
} }

Stack using interface

public interface StackImp


{
public abstract void push(int no);
public abstract void pop();
public abstract void display();
public abstract void menu();
}
import java.util.Scanner;
class StackStick implements StackImp
{
Scanner sc=new Scanner(System.in);
int a[]=new int[50];
int top,max;
StackStick(int max1)
{
max=max1;
top=-1;
}
public void push(int no)
{
if(top==max-1)
System.out.println("Stack overflow");
else
a[++top]=no;
}
public void pop()
{
if(top==-1)
{
System.out.println("Stack empty");
}
else
System.out.println(a[top--]);
}
public void display()
{
int i;
for(i=top;i>=0;i--)
System.out.println(a[i]);
}
public void menu()
{
int num,ch;
while(true)
{
System.out.println("1:Push");
System.out.println("2:Pop");
System.out.println("3:Display");
System.out.println("4:Exit");
System.out.println("Enter choice");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number");
push(sc.nextInt());
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid input");
}
}
}
public static void main(String args[])
{
StackStick m=new StackStick(5);
m.menu();
}
}
Polymorphism in Java
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.

Polymorphism is the capability of a method to do different things based on the object that it is
acting upon. The program need not know the exact type of object in advance, so that the
behavior can be implemented at the run time called Late Binding or Dynamic Binding.
Polymorphic Method is a method which behaves differently when it is invoked on different
objects
There are two types of polymorphism in Java:
1. Compile-time Polymorphism : If you overload a static method in Java, it is the
example of compile time polymorphism
2. Runtime polymorphism: If method invocation is determined by the JVM (at the run-tim
not compiler, it is known as Runtime / Late Binding/ Dynamic Polymorphism

Note: We can perform polymorphism in java by method overloading and method overriding.

An illustration of static polymorphism


The compiler chooses the proper add method at build-time (Compilation Time)
because Java chooses the right method to call depending on the number, type and the
order of input to the method. (Method Overloading-Compile-time Polymorphism)

1. public class Calculator {


2. public int add(int a, int b) {
3. return a + b;
4. }
5. public double add(double a, double b) {
6. return a + b;
7. }
8. public int add(int a, int b, int c) {
9. return a + b + c;
10. }
11. public static void main(String[] args)
12. {
13. Calculator calculator = new Calculator();
14. System.out.println(calculator.add(5, 10));
15. System.out.println(calculator.add(2.5, 3.7));
16. System.out.println(calculator.add(1, 2, 3));
17. }
18. }

An illustration of Dynamic polymorphism or Runtime polymorphism 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. Method Overriding- Runtime Polymorphism)
Example 1
1. class Bank
2. { float getRateOfInterest()
3. {return 0;}
4. }
5. -----------------------------
6. class SBI extends Bank
7. { float getRateOfInterest()
8. {return 8.4f;}
9. }
10. -----------------------------
11. class ICICI extends Bank
12. { float getRateOfInterest(){return 7.3f;}
13. }
14. class AXIS extends Bank
15. {
16. float getRateOfInterest()
17. {return 9.7f;}
18. }
19. class TestPolymorphism
20. { public static void main(String args[]){
21. Bank b;
22. b=new SBI();
23. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
24. b=new ICICI();
25. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
26. b=new AXIS();
27. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
28. }
29. }
Test it Now
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Example 2

class Shape
{
int x,y;
void Area()
{System.out.pritnln(“ABC”);
}
}
//--------------------
class Square extends Shape
{
int l=2;
void area()
{
System.out.println(l*l);
}
}
//---------------------
class Rectangle extends Shape
{ int l=2,b=3;
void area()
{ System.out.println(l*b);
}
}
//-------------------
class Circle extends Shape
{ int radius=5;
void area()
{ System.out.println(3.14*radius*radius);
}
}
//-------------------
class Polymorphism
{ public static void main(String[] args)
{ Shape s1;
s1 = new Shape();
s1.area();
s1 = new Square();
s1.area();
s1 = new Rectangle();
s1.area();
s1 = new Circle();
s1.area();

}}

Abstract Class Interface


• Abstract keyword is used • An interface keyword is used
to create abstract class. to declare an interface.
• Abstract class extends • An interface can be
using the keyword extends. implement using the
• An abstract class cannot keyword implement
support Multiple inheritance. • An interface supports
• An abstract variables can be Multiple inheritance.
public, non-final, final and
non-static. • An interface variables are
• An abstract method can be public, static and final by default.
public, protected and not • An interface method are public
static and private.
and abstract

Polymorphism
• It does not need any
keyword to create the base
class
• In polymorphism the object
of the base class can be
created
• Methods in the base class
of polymorphism can
contain statements.
• Variables in Java
do not follow
polymorphism.
• Overriding is
applied only to
the method and
not the variables

You might also like