2. • Inheritance is the mechanism in java by which one class acquires the features(fields and
methods) of another class.
Important terminology:
• Super Class: The class whose features are inherited is known as super class(or a base class
or a parent class).
• Sub Class: The class that inherits the other class is known as sub class(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to
the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
• The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
3. class Employee{
float salary=4000;
}
class Programmer extends Employee{
int bonus=1000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary); //parent class variable
System.out.println("Bonus of Programmer is:"+p.bonus); /child class variable
}
}
4. class Calculation
{
int z;
public void addition(int x, int y)
{ z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{ z = x - y;
System.out.println("The difference between the given numbers:"+z);
} }
public class My_Calculation extends Calculation
{
public void multiplication(int x, int y)
{ z = x * y;
System.out.println("The product of the given numbers:"+z); }
public static void main(String args[])
{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b); } }
5. • Child class objects has variables/methods of parent class as well as itself.
6. 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.
Multiple inheritance is not supported using classes in java.
7.
8. SINGLE INHERITANCE
• In single inheritance, subclasses inherit the features of one superclass. In image below,
the class A serves as a base class for the derived class B.
9. class Animal{
void eats(){System.out.println(“All animals eat...");}
}
class Dog extends Animal{
void barks(){System.out.println(“only dogs barks...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.barks();
d.eats();
}
}
10. class one
{
public void print_one()
{
System.out.println(“Kristu");
}
}
class two extends one
{
public void print_ftwo()
{
System.out.println(“Jayanti");
}
}
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_one();
g.print_two();
}
}
11. MULTILEVEL INHERITANCE
• In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class.
• In below image, the class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.
12. class Animal{
void eat()
{System.out.println(“All animals eat...");}
}
class Dog extends Animal{
Void bark()
{System.out.println(“Only dogs barkis");}
}
class BabyDog extends Dog{
void weep()
{System.out.println(“Baby dogs weep");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
13. class one
{
public void print_one()
{ System.out.println(“Kristu"); }
}
class two extends one
{
public void print_two()
{ System.out.println(“Jayanti"); }
}
class three extends two
{
public void print_three()
{ System.out.println(“College"); }
}
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_one();
g.print_two();
g.print_three();
}
}
14. HIERARCHICAL INHERITANCE
• In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.
• In below image, the class A serves as a base class for the derived class B,C and D.
15. class one
{
public void print_one)
{
System.out.println(“Kristu");
}
}
class two extends one
{
public void print_two()
{
System.out.println(“Jayanti");
}
}
class three extends one
{
/*............*/
}
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_one();
two t = new two();
t.print_two();
g.print_one();
}
}
16. class A {
public void methodA() {
System.out.println("method of Class A");
}
}
class B extends A {
public void methodB() {
System.out.println("method of Class B");
}
}
class C extends A {
public void methodC() {
System.out.println("method of Class C");
}
}
class D extends A {
public void methodD() {
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of
class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
17. METHOD OVERRIDING
• Declaring a method in sub class which is already present in parent class is known as
method overriding, provided that it is not marked final..
• Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class.
• In this case the method in parent class is called overridden method and the method in
child class is called overriding method.
• The version of a method that is executed will be determined by the object that is used to
invoke it. If an object of a parent class is used to invoke the method, then the version in
the parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed.
• In other words, it is 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.
18. 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 robject
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
}
}
19. • A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.
• Constructors cannot be overridden.
• The access level cannot be more restrictive than the overridden method's access level.
For example: If the superclass method is declared public then the overridding method in
the sub class cannot be either private or protected.
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
20. class Parent {
// private methods are not overridden
private void m1()
{
System.out.println("From parent m1()"); }
protected void m2()
{
System.out.println("From parent m2()"); }
}
class Child extends Parent {
// new m1() method ,unique to Child class
private void m1()
{
System.out.println("From child m1()");
}
// overriding method with more accessibility
public void m2()
{
System.out.println("From child m2()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Child obj2 = new Child();
Parent obj3=new Child();//Upcasting
obj2.m2(); //overriding
obj3.m2();
}
}
21. • When Parent class reference variable refers to Child class object, it is known
as Upcasting.
• In Java this is helpful in scenarios where multiple child classes extends one parent class.
In those cases we can create a parent class reference and assign child class objects to it.
22. DYNAMIC METHOD DISPATCH OR RUNTIME POLYMORPHISM
• 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.
•
23. class Game
{
public void type()
{
System.out.println("Indoor & outdoor");
}
}
Class Cricket extends Game
{
public void type()
{
System.out.println("outdoor game");
}
}
Class dynamicdispatch{
public static void main(String[] args)
{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm = ck;//gm refers to Cricket object,dynamic
method dispatch
gm.type(); //calls Cricket's version of type
}
}
24. class Shape{
void draw(){System.out.println("drawing..");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle..");
}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
25. OVERLOADING
• Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different.
• 1. Number of parameters.
For example: This is a valid case of overloading
add(int, int) add(int, int, int)
• 2. Data type of parameters.
For example:add(int, int) add(int, float)
• 3. Sequence of Data type of parameters.
For example:add(int, float) add(float, int)
• Invalid case of method overloading:if two methods have same name, same parameters
and have different return type, then this is not a valid method overloading example. This
will throw compilation error.
int add(int, int) float add(int, int)
26. • Method overloading is an example of Static Polymorphism.
• Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static
binding where binding of method call to its definition happens at Compile time.
27. class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num) //different number of parameters
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
28. class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)different type of paarameter
{
System.out.println(c );
}
}
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
29. class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)//different sequence of parameters
{
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
30. ABSTRACT CLASS AND ABSTRACT METHOD
• 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.
• 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 subclass not to change the body of the
method.
• A method which is declared as abstract and does not have implementation is known as an
abstract method.
• If a class includes abstract methods, then the class itself must be declared abstract
31. abstract class Shape{
abstract void draw();
public void nonabstract(){
System.out.println(“Non abstrat method");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
class AbstractionTest1{
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
s.nonabstractmethod();
}
}
32. SUPER KEYWORD
• The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
33. Use of super with variables
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class
(vehicle) */
System.out.println("Maximum Speed: " +
super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
34. • Use of super with methods
class Person
{
void message()
{
System.out.println("This is person class");
}
}
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
void display()
{ // will invoke or call current class message()
method
message();
// will invoke or call parent class message()
method
super.message();
}
}
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
35. Use of super with constructors
class Person
{
Person()
{
System.out.println("Person class
Constructor");
}
}
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class
Constructor");
}
}
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
36. • Call to super() must be first statement in Derived(Student) Class
constructor.
• If a constructor does not explicitly invoke a superclass constructor, the
Java compiler automatically inserts a call to the no-argument
constructor of the superclass.
• If the superclass does not have a no-argument constructor, you will
get a compile-time error.
• If a subclass constructor invokes a constructor of its superclass, either
explicitly or implicitly, a whole chain of constructors called, all the way
back to the constructor of Object. This, in fact, is the case. It is
called constructor chaining..
37. THIS KEYWORD
• ‘this’ is a reference variable that refers to the current object.
• The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name
• Invoke current class constructor
• Invoke current class method
38. class Test
{
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
}
class ThisEx1{
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display();
}
}
39. class Test
{
int a;
int b;
//Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor n");
}
//Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized
constructor");
}
}
Class thisEx2{
public static void main(String[] args)
{
Test object = new Test();
}
}