Inheritance using Java
Dr. Arul Xavier V M
Why do we need Inheritance?
Classical Analog Watch Modern Digital Watch
Why do we need Inheritance?
⚫ Classical Analog Watch Functions
Why do we need Inheritance?
⚫ Modern Digital Watch Functions
Why do we need Inheritance?
⚫ Code duplication
Inheritance
⚫ Reduce code duplication – Enhance Code Reusability
What is Inheritance in Java?
⚫ In Java, Inheritance is a procedure used to inherit all the
properties of parent class(super class) by the child
class(sub class).
How to implement Inheritance in java?
⚫ The extends keyword indicates that you are making a new class that
derives from an existing class.
⚫ In the terminology of Java, a class that is inherited is called a super
class. The new class is called a subclass.
class super_classname {
// data and methods
}
class sub_classname extends super_classname
{
// data and methods of super_classname
// data and methods of sub_classname
}
8
Example 1-
class Dad {
int cash = 10000;
}
class Son extends Dad {
}
class Sample{
public static void main(String[] args)
{
Son s1 = new Son();
System.out.println(s1.cash);
}
}
Exercise 2
class BankAccount {
int accno;
String name;
double balance;
}
class SavingsAccount extends BankAccount
{
double interestrate;
}
class Sample
{
public static void main(String[] args) {
SavingsAccount sb=new SavingsAccount();
System.out.println(sb.accno);
System.out.println(sb.balance);
System.out.println(sb.interestrate);
}
}
Types of Inheritance
Single Inheritance class BankAccount
{
}
class SavingsAccount extends BankAccount
{
}
Multi-Level Inheritance
class Person
{
}
class Employee extends Person
{
}
class Manager extends Employee
{
}
Types of Inheritance
Hierarchical Inheritance class BankAccount
{
}
class SavingsAccount extends BankAccount
{
}
class CurrentAccount extends BankAccount
{
}
Hybrid Inheritance class Person { }
class Employee extends Person { }
class Manager extends Employee { }
class Engineer extends Employee { }
class Director extends Manager { }
What type of inheritance is this?
class A { }
class B extends A { }
class C extends A { }
A. Multilevel inheritance
B. Single inheritance
C. Hierarchical inheritance
D. Hybrid inheritance
Multiple inheritance is not supported in
java!!!
14
super Keyword
⚫ In java, super keyword is reference to the super class.
⚫ super() - to call super class constructor ( it is automatically
added by the compiler)
⚫ super - access super class data and methods from sub class
15
Use of super() – Constructor Chaining
class BankAccount {
int accno;
String name;
double balance;
BankAccount()
{
}
}
class SavingsAccount extends BankAccount {
double interestrate;
SavingsAccount(){
super(); //calls super class constructor
}
}
class MainClass {
public static void main(String[] args) {
SavingsAccount sb=new SavingsAccount();
}
}
super() call is implicit!!!
class Person{
String name;
String gender;
Person()
{
System.out.println("Person Constructor");
}
}
class Employee extends Person{
int empid;
double salary;
Employee()
{
System.out.println("Employee Constructor");
}
void display() {
System.out.println(name+" "+gender+" "+empid+" "+salary);
}
}
public class Sample {
public static void main(String[] args) {
Employee e = new Employee();
e.display();
}
}
17
super() method with parameters
class BankAccount
{
int accno;
String name;
double balance;
BankAccount(int accno,String name,double balance)
{
this.accno = accno;
this.name = name;
this.balance = balance;
}
}
class SavingsAccount extends BankAccount
{
double interestrate;
SavingsAccount(int accno,String name,double balance,double interestrate)
{
super(accno,name,balance);
this.interestrate = interestrate;
}
}
class Sample
{
public static void main(String[] args) {
SavingsAccount sb=new SavingsAccount(101,"John",10000,7.5);
}
}
Find the output
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super();
System.out.println("Child Constructor");
}
}
public class Test {
public static void main(String[] args) {
new Child();
}
}
A. Child Constructor
Parent Constructor
B. Parent Constructor
Child Constructor
C. Child Constructor
D. Parent Constructor
B. Parent Constructor
Child Constructor
Find the output
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
System.out.println("Child Constructor");
}
}
public class Test {
public static void main(String[] args) {
new Child();
}
}
A. Child Constructor
Parent Constructor
B. Parent Constructor
Child Constructor
C. Child Constructor
D. Parent Constructor
B. Parent Constructor
Child Constructor
Method Overriding in Java
⚫ Method overriding is the process of redefining the
inherited method of super class inside sub class.
⚫ specific implementation of a method that is already provided by its
super class.
⚫ Method overriding is used for runtime polymorphism
⚫ Rules for Java Method Overriding
⚫ sub class method must have same name as in the parent class
⚫ sub class method must have same parameter as in the parent
class.
21
22
class Shape // super class
{
int length, height;
Shape(int length,int height){
this.length = length;
this.height = height;
}
void findArea() {
System.out.println("Area = Undefined");
}
}
Example: Method Overriding
class Rectangle extends Shape // sub class
{
Rectangle(int length,int height)
{
super(length,height);
}
void findArea()
{
System.out.println("Area = " + (length*height));
}
}
public class MainApp {
public static void main(String[] args) {
Rectangle r = new Rectangle(10,5);
r.findArea();
}
}
class Animal {
void eat() {
System.out.println("Animal eating..");
}
}
class Cat extends Animal {
void eat() {
System.out.println("Cat eating..");
}
}
class Sample
{
public static void main(String[] args) {
Cat cat = new Cat()
cat.eat();
}
}
Find the output?
Answer: Cat eating..
Run time Polymorphism
⚫ The word comes from poly (many) + morph (forms).
⚫ It means the same method behaves differently depending on the actual
object type.
⚫ Rules of implementing polymorphism using inheritance
⚫ Method Overriding.
⚫ Assign sub class object to super class reference variable.
⚫ Call the overriding method using super class reference variable.
Dynamic Method Dispatch / Run Time Polymorphism
⚫ Runtime polymorphism or Dynamic Method Dispatch is a process
in which a call to an overridden method by super class reference
variable is resolved at run time rather than compile-time.
⚫ In this process, an overridden method is called through the reference
variable of a super class.
⚫ The determination of the method to be called is based on the object
being referred by the reference variable.
25
Example
Employee
Engineer
Manager
calcSalary()
calcSalary() calcSalary()
Consider Employee class and two sub class Manager and Engineer. Employee class having
generic method to calculate salary which inherited and overriden by Manager and Engineer
since salary calculation will be different for Manager and Engineer(having different bonus).
To achieve run time polymorphism,
Store the manager object and engineer object
using super class reference (Employee) variable
which dynamically dispatch the call based on
object type.
26
class Employee
{
int salary = 10000;
void calSalary() {
System.out.println("Salary:"+salary);
}
}
class Manager extends Employee {
int bonus=5000;
void calSalary() {
System.out.println("Manager Salary:"+(salary+bonus));
}
}
class Engineer extends Employee {
int incentive=3000;
void calSalary() {
System.out.println("Engineer Salary:"+(salary+incentive));
}
}
class Sample {
public static void main(String[] args) {
//Assign sub class object to super class variable
Employee emp = null;
emp = new Manager();
emp.calSalary(); // polymorphism call
emp = new Engineer();
emp.calSalary(); // polymorphism call
}
}
class Animal {
void eat() {
System.out.println("Animal eating..");
}
}
class Cat extends Animal {
void eat() {
System.out.println("Cat eating..");
}
}
class Tiger extends Animal {
void eat() {
System.out.println("Tiger eating..");
}
} class Sample
{
public static void main(String[] args) {
Animal a = new Animal()
a = new Tiger();
a.eat();
}
}
Find the output?
Answer: Tiger eating..
29
class Shape {
int length, height;
Shape(int length,int height){
this.length = length;
this.height = height;
}
void findArea() {
System.out.println("Area = Undefined");
}
}
class Rectangle extends Shape {
Rectangle(int length,int height) {
super(length,height);
}
void findArea() {
System.out.println("Rectangle Area = " + (length*height));
}
}
class Triangle extends Shape {
Triangle(int length,int height) {
super(length,height);
}
void findArea() {
System.out.println("Triangle Area = " + (0.5 * length*height));
}
}
public class MainClass {
public static void main(String[] args) {
//Super class reference variable
// polymorphic variable
Shape ob = null;
ob = new Rectangle(10,5);
ob.findArea();
ob = new Triangle(20,10);
ob.findArea();
}
}
Sample MCQs
Predict the output
class Employee {
private int id = 101;
public int getId() {
return id;
}
}
public class Company {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp.id);
}
}
A) 101
B) 0
C) Compilation error
D) Runtime exception
C) Compilation error
Reason:- id is a private variable
Find the output
class Employee {
double salary;
Employee() {
salary = 0;
}
Employee(int data) {
salary = data;
}
Employee(double data) {
salary = data;
}
}
class Main {
public static void main(String[] args)
{
Employee e=new Employee(100.0);
System.out.println(e.salary);
}
}
A. 0.0
B. 0
C.100.0
D.Compilation Fails
Answer: C) 100.0
Which code to be used at line x to correctly execute the code?
class Circle {
int radius;
Circle(int data) {
radius = data;
}
}
class Main {
public static void main(String[] args) {
//line x
System.out.println(obj.radius);
}
}
A. Circle obj = new Circle(5.5);
B. Circle obj = new Circle(5);
C. Circle obj = new Circle();
D. Circle obj = new Circle(5, 5.5);
Answer: B) Circle obj = new Circle(5);
String Handing MCQ
1. Find the output?
String s = "HELLO";
System.out.println(s.charAt(1));
A. H
B. E
C. L
D. O
Answer: B) E
⚫ Find the output
String str = "JavaProgramming";
System.out.println(str.substring(4, 11));
A. Progra
B. Program
C. gramming
D. aProgram
Answer: B) Program
⚫ Find the output
String s = "apple";
System.out.println(s.replace('p', 'b'));
A. abble
B. abblee
C. abbbe
D. abbe
Answer: A) abble
⚫ Find the output
String s = "one two one";
System.out.println(s.replaceFirst("one", "ONE"));
A. ONE two ONE
B. ONE two one
C. one two ONE
D. ONE ONE ONE
Answer: B) ONE two one
Find the output
String s = "apple,orange,banana";
String[] arr = s.split(",");
System.out.println(arr[2]);
A. orange
B. banana
C. apple
D. nu
Answer: B) banana
Find the output
String s1 = "Java";
String s2 = "java";
System.out.println(s1.equals(s2));
A. true
B. false
C. compile error
D. null
Answer: B) false
Find the output
String s1 = "Java";
String s2 = "java";
System.out.println(s1.equalsIgnoreCase(s2));
A. true
B. false
C. compile error
D. null
Answer: A) true
⚫ Find the output
String s = "HelloWorld";
System.out.println(s.contains("World"));
A. true
B. false
C. compile error
D. null
Answer: A) true

Inheritance in Java for engineerign students

  • 1.
  • 2.
    Why do weneed Inheritance? Classical Analog Watch Modern Digital Watch
  • 3.
    Why do weneed Inheritance? ⚫ Classical Analog Watch Functions
  • 4.
    Why do weneed Inheritance? ⚫ Modern Digital Watch Functions
  • 5.
    Why do weneed Inheritance? ⚫ Code duplication
  • 6.
    Inheritance ⚫ Reduce codeduplication – Enhance Code Reusability
  • 7.
    What is Inheritancein Java? ⚫ In Java, Inheritance is a procedure used to inherit all the properties of parent class(super class) by the child class(sub class).
  • 8.
    How to implementInheritance in java? ⚫ The extends keyword indicates that you are making a new class that derives from an existing class. ⚫ In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass. class super_classname { // data and methods } class sub_classname extends super_classname { // data and methods of super_classname // data and methods of sub_classname } 8
  • 9.
    Example 1- class Dad{ int cash = 10000; } class Son extends Dad { } class Sample{ public static void main(String[] args) { Son s1 = new Son(); System.out.println(s1.cash); } }
  • 10.
    Exercise 2 class BankAccount{ int accno; String name; double balance; } class SavingsAccount extends BankAccount { double interestrate; } class Sample { public static void main(String[] args) { SavingsAccount sb=new SavingsAccount(); System.out.println(sb.accno); System.out.println(sb.balance); System.out.println(sb.interestrate); } }
  • 11.
    Types of Inheritance SingleInheritance class BankAccount { } class SavingsAccount extends BankAccount { } Multi-Level Inheritance class Person { } class Employee extends Person { } class Manager extends Employee { }
  • 12.
    Types of Inheritance HierarchicalInheritance class BankAccount { } class SavingsAccount extends BankAccount { } class CurrentAccount extends BankAccount { } Hybrid Inheritance class Person { } class Employee extends Person { } class Manager extends Employee { } class Engineer extends Employee { } class Director extends Manager { }
  • 13.
    What type ofinheritance is this? class A { } class B extends A { } class C extends A { } A. Multilevel inheritance B. Single inheritance C. Hierarchical inheritance D. Hybrid inheritance
  • 14.
    Multiple inheritance isnot supported in java!!! 14
  • 15.
    super Keyword ⚫ Injava, super keyword is reference to the super class. ⚫ super() - to call super class constructor ( it is automatically added by the compiler) ⚫ super - access super class data and methods from sub class 15
  • 16.
    Use of super()– Constructor Chaining class BankAccount { int accno; String name; double balance; BankAccount() { } } class SavingsAccount extends BankAccount { double interestrate; SavingsAccount(){ super(); //calls super class constructor } } class MainClass { public static void main(String[] args) { SavingsAccount sb=new SavingsAccount(); } }
  • 17.
    super() call isimplicit!!! class Person{ String name; String gender; Person() { System.out.println("Person Constructor"); } } class Employee extends Person{ int empid; double salary; Employee() { System.out.println("Employee Constructor"); } void display() { System.out.println(name+" "+gender+" "+empid+" "+salary); } } public class Sample { public static void main(String[] args) { Employee e = new Employee(); e.display(); } } 17
  • 18.
    super() method withparameters class BankAccount { int accno; String name; double balance; BankAccount(int accno,String name,double balance) { this.accno = accno; this.name = name; this.balance = balance; } } class SavingsAccount extends BankAccount { double interestrate; SavingsAccount(int accno,String name,double balance,double interestrate) { super(accno,name,balance); this.interestrate = interestrate; } } class Sample { public static void main(String[] args) { SavingsAccount sb=new SavingsAccount(101,"John",10000,7.5); } }
  • 19.
    Find the output classParent { Parent() { System.out.println("Parent Constructor"); } } class Child extends Parent { Child() { super(); System.out.println("Child Constructor"); } } public class Test { public static void main(String[] args) { new Child(); } } A. Child Constructor Parent Constructor B. Parent Constructor Child Constructor C. Child Constructor D. Parent Constructor B. Parent Constructor Child Constructor
  • 20.
    Find the output classParent { Parent() { System.out.println("Parent Constructor"); } } class Child extends Parent { Child() { System.out.println("Child Constructor"); } } public class Test { public static void main(String[] args) { new Child(); } } A. Child Constructor Parent Constructor B. Parent Constructor Child Constructor C. Child Constructor D. Parent Constructor B. Parent Constructor Child Constructor
  • 21.
    Method Overriding inJava ⚫ Method overriding is the process of redefining the inherited method of super class inside sub class. ⚫ specific implementation of a method that is already provided by its super class. ⚫ Method overriding is used for runtime polymorphism ⚫ Rules for Java Method Overriding ⚫ sub class method must have same name as in the parent class ⚫ sub class method must have same parameter as in the parent class. 21
  • 22.
    22 class Shape //super class { int length, height; Shape(int length,int height){ this.length = length; this.height = height; } void findArea() { System.out.println("Area = Undefined"); } } Example: Method Overriding class Rectangle extends Shape // sub class { Rectangle(int length,int height) { super(length,height); } void findArea() { System.out.println("Area = " + (length*height)); } } public class MainApp { public static void main(String[] args) { Rectangle r = new Rectangle(10,5); r.findArea(); } }
  • 23.
    class Animal { voideat() { System.out.println("Animal eating.."); } } class Cat extends Animal { void eat() { System.out.println("Cat eating.."); } } class Sample { public static void main(String[] args) { Cat cat = new Cat() cat.eat(); } } Find the output? Answer: Cat eating..
  • 24.
    Run time Polymorphism ⚫The word comes from poly (many) + morph (forms). ⚫ It means the same method behaves differently depending on the actual object type. ⚫ Rules of implementing polymorphism using inheritance ⚫ Method Overriding. ⚫ Assign sub class object to super class reference variable. ⚫ Call the overriding method using super class reference variable.
  • 25.
    Dynamic Method Dispatch/ Run Time Polymorphism ⚫ Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method by super class reference variable is resolved at run time rather than compile-time. ⚫ In this process, an overridden method is called through the reference variable of a super class. ⚫ The determination of the method to be called is based on the object being referred by the reference variable. 25
  • 26.
    Example Employee Engineer Manager calcSalary() calcSalary() calcSalary() Consider Employeeclass and two sub class Manager and Engineer. Employee class having generic method to calculate salary which inherited and overriden by Manager and Engineer since salary calculation will be different for Manager and Engineer(having different bonus). To achieve run time polymorphism, Store the manager object and engineer object using super class reference (Employee) variable which dynamically dispatch the call based on object type. 26
  • 27.
    class Employee { int salary= 10000; void calSalary() { System.out.println("Salary:"+salary); } } class Manager extends Employee { int bonus=5000; void calSalary() { System.out.println("Manager Salary:"+(salary+bonus)); } } class Engineer extends Employee { int incentive=3000; void calSalary() { System.out.println("Engineer Salary:"+(salary+incentive)); } } class Sample { public static void main(String[] args) { //Assign sub class object to super class variable Employee emp = null; emp = new Manager(); emp.calSalary(); // polymorphism call emp = new Engineer(); emp.calSalary(); // polymorphism call } }
  • 28.
    class Animal { voideat() { System.out.println("Animal eating.."); } } class Cat extends Animal { void eat() { System.out.println("Cat eating.."); } } class Tiger extends Animal { void eat() { System.out.println("Tiger eating.."); } } class Sample { public static void main(String[] args) { Animal a = new Animal() a = new Tiger(); a.eat(); } } Find the output? Answer: Tiger eating..
  • 29.
    29 class Shape { intlength, height; Shape(int length,int height){ this.length = length; this.height = height; } void findArea() { System.out.println("Area = Undefined"); } } class Rectangle extends Shape { Rectangle(int length,int height) { super(length,height); } void findArea() { System.out.println("Rectangle Area = " + (length*height)); } } class Triangle extends Shape { Triangle(int length,int height) { super(length,height); } void findArea() { System.out.println("Triangle Area = " + (0.5 * length*height)); } } public class MainClass { public static void main(String[] args) { //Super class reference variable // polymorphic variable Shape ob = null; ob = new Rectangle(10,5); ob.findArea(); ob = new Triangle(20,10); ob.findArea(); } }
  • 30.
  • 31.
    Predict the output classEmployee { private int id = 101; public int getId() { return id; } } public class Company { public static void main(String[] args) { Employee emp = new Employee(); System.out.println(emp.id); } } A) 101 B) 0 C) Compilation error D) Runtime exception C) Compilation error Reason:- id is a private variable
  • 32.
    Find the output classEmployee { double salary; Employee() { salary = 0; } Employee(int data) { salary = data; } Employee(double data) { salary = data; } } class Main { public static void main(String[] args) { Employee e=new Employee(100.0); System.out.println(e.salary); } } A. 0.0 B. 0 C.100.0 D.Compilation Fails Answer: C) 100.0
  • 33.
    Which code tobe used at line x to correctly execute the code? class Circle { int radius; Circle(int data) { radius = data; } } class Main { public static void main(String[] args) { //line x System.out.println(obj.radius); } } A. Circle obj = new Circle(5.5); B. Circle obj = new Circle(5); C. Circle obj = new Circle(); D. Circle obj = new Circle(5, 5.5); Answer: B) Circle obj = new Circle(5);
  • 34.
    String Handing MCQ 1.Find the output? String s = "HELLO"; System.out.println(s.charAt(1)); A. H B. E C. L D. O Answer: B) E
  • 35.
    ⚫ Find theoutput String str = "JavaProgramming"; System.out.println(str.substring(4, 11)); A. Progra B. Program C. gramming D. aProgram Answer: B) Program
  • 36.
    ⚫ Find theoutput String s = "apple"; System.out.println(s.replace('p', 'b')); A. abble B. abblee C. abbbe D. abbe Answer: A) abble
  • 37.
    ⚫ Find theoutput String s = "one two one"; System.out.println(s.replaceFirst("one", "ONE")); A. ONE two ONE B. ONE two one C. one two ONE D. ONE ONE ONE Answer: B) ONE two one
  • 38.
    Find the output Strings = "apple,orange,banana"; String[] arr = s.split(","); System.out.println(arr[2]); A. orange B. banana C. apple D. nu Answer: B) banana
  • 39.
    Find the output Strings1 = "Java"; String s2 = "java"; System.out.println(s1.equals(s2)); A. true B. false C. compile error D. null Answer: B) false
  • 40.
    Find the output Strings1 = "Java"; String s2 = "java"; System.out.println(s1.equalsIgnoreCase(s2)); A. true B. false C. compile error D. null Answer: A) true
  • 41.
    ⚫ Find theoutput String s = "HelloWorld"; System.out.println(s.contains("World")); A. true B. false C. compile error D. null Answer: A) true