Inheritance notes
Inheritance notes
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.
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
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.
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.
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
Do's
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:
Interface
.
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
• 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)
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).
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.
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
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 --------
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();
} }
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.
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();
}}
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