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

module-6 (2)

Uploaded by

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

module-6 (2)

Uploaded by

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

Object-Oriented Programming

Inheritance in Java

This lesson introduces the process of acquiring the properties and


functionalities of another class, otherwise called Inheritance. There are four
types of inheritance, single, multilevel, hierarchical, multiple and
hybrid. This particular lesson will give an insight into various usage and rules
of Inheritance. The flow of execution for inheritance as well as its syntax will
be presented. Sample code fragments will also be presented to demonstrate
how inheritance works. Problem sets will be given at the end of the lesson to
give you time to practice before taking the assessment tasks.

Learning Outcomes:

At the end of the lesson, you are expected to:


 Define super classes and subclasses
 Evaluate the output of code fragments having different types of
inheritance
 Create inheritance programs

Start your lesson here.

Inheritance is an integral part and important pillar of Java OOPs which


lets the properties of one class to be inherited by the other class. It is the
process by which one class acquires the properties (data members) and
functionalities(methods) of another class. The aim of inheritance is to
provide the reusability of code so that a class has to write only the unique
features and rest of the common properties and functionalities can be
extended from the another class.
The biggest advantage of Inheritance is that the code that is
already present in base class need not be rewritten in the child class,
otherwise called Reusability. This means that the data members (instance
variables) and methods of the parent class can be used in the child class.
Once a behavior (method) is defined in a superclass, that behavior is
automatically inherited by all subclasses. Thus, you can encode a method
Object-Oriented Programming

only once and they can be used by all subclasses. A subclass only needs to
implement the differences between itself and the parent.

In real life scenario, a child inherits the properties from his parents. A
similar concept is followed in Inheritance in Java, where it has two classes:

1. Parent class ( Super or Base class )


 The class whose properties and functionalities are
used(inherited) by another class is known as parent class, super
class or Base class.
2. Child class ( Subclass or Derived class )
 The class that extends the features of another class is known as
child class, sub class or derived class.
* Another commonly used term for inheritance is specialization and
generalization. A subclass is a specialization of a superclass, and a superclass
is a generalization of one or more subclasses.

The inheritance syntax is:

class mother
{
// body of the program
}
class daughter extends mother
{
// body of the program
}

Where:
class mother – is the parent class
class daughter – is the child class
extends – is the keyword used to derive a class and inherits the
properties and methods of the parent class.

In order to illustrate this, lets create a sample parent class. Suppose


we have a parent class called compute with three methods called sum
and difference with two parameters int num1 and int num2.
class compute
Object-Oriented Programming

{
int total;

public void Sum(int num1, int num2)


{
total = num1+num2;
System.out.println("The sum of the two numbers is:"+total);
}

public void Difference(int num1,int num2)


{
total = num1-num2;
System.out.println("The difference between the two numbers
is:"+total);
}
}

Now, we want to create another class named ComputeProd. Since


the body of the program of class ComputeProd is also arithmetic operation,
we decide to just extend the class compute, so that we can inherit all the
properties and methods of the existing class compute. To do this, we write
class ComputeProd extends compute {

public void Product(int num1, int num2)


{
total = num1*num2;
System.out.println("The product of the two numbers is:"+total);
}

When a ComputeProd object (getTotal) is instantiated, the superclass


is invoked implicitly to do the necessary initializations. After that, the
statements inside the subclass's are executed. To illustrate this, consider the
following code,

public static void main(String args[])


{
ComputeProd getTotal = new ComputeProd ();
int one = 30, two = 5;
getTotal.Sum(one, two);
getTotal.Difference(one, two);
getTotal.Product(one, two);
Object-Oriented Programming

}
}

In the code, we create an object of class ComputeProd called


getTotal. The output of the program is:
The sum of the given numbers: 35
The difference between the given numbers: 25
The product of the given numbers: 150

Now take a look at the complete code below.


class compute // first class
{
int total;

public void Sum(int num1, int num2) // first method with


parameter
{
total = num1+num2;
System.out.println("The sum of the two numbers is:"+total);
}

public void Difference(int num1,int num2) // second method with


parameter
{
total = num1-num2;
System.out.println("The difference between the two numbers
is:"+total);
}

public static void main(String args[])


{
ComputeProd getTotal = new ComputeProd ();
int one = 30, two = 5;
getTotal.Sum(one, two);
getTotal.Difference(one, two);
getTotal.Product(one, two);
}
}
class ComputeProd extends compute // second class with extends
keyword
{
public void Product(int num1, int num2)
{
total = num1*num2;
System.out.println("The product of the two numbers is:"+total);
}
}
TYPES OF INHERITANCE
Object-Oriented Programming

1. SINGLE INHERITANCE

CLASS A public class A


{
…………
}
public class B extends A
CLASS B {
……………
}

Single Inheritance refers to a child and parent class relationship


where a class extends the another class.
 Take a look at sample code below:
import java.io.*;
class Animal
{
void eat()
{
System.out.println(“eating”);
}
}

class Dog extends Animal


{
void bark()
{
System.out.println(“barking”);
}

public static void main(String args[])


{
Dog browny =new Dog();
browny.bark();
browny.eat();
}
}
The output is:
barking
eating

Where the class animal is the parent class with a method name eat, while the
class dog is a child class which extends the parent class animal. Inside the main
method, an object name browny was created to implicitly invoked superclass or
parent class.

2. MULTI- LEVEL INHERITANCE public class A


{
CLASS A …………
}
public class B extends A
{
CLASS B ……………
}
Object-Oriented Programming

Multi-level inheritance refers to a child and parent class relationship


where a class extends the child class. For example class C extends class B
and class B extends class A.
 Note: In real life scenario, the multilevel inheritance is same with
grandparent and grandchildren relationship.
Take a look at sample code below.
class Animal
{
void eat()
{
System.out.println(“eating…”);
}
}

class Dog extends Animal


{
void bark()
{
System.out.println(“barking…”);
}
}

class Puppy extends Dog


{
void weep()
{
System.out.println(“weeping…”);
}

public static void main(String args[])


{
Puppy dagul=new Puppy();
dagul.weep();
dagul.bark();
dagul.eat();
}
}
The output is:
weeping
barking
Object-Oriented Programming

eating

3. HIERARCHICAL INHERITANCE
public class A
{
CLASS A …………
}
public class B extends A
{
……………
}
CLASS B CLASS C
public class C extends A
{
……..
}
Hierarchical inheritance refers to a child and parent class
relationship where more than one classes extends the same class. For
example, classes B and C extends the same class A.
* NOTE: In real life scenario, the hierarchical inheritance is same with parent and
children(siblings) relationship where their parent is class A while the class B and class C
are the children (class B and class C are siblings).
Take a look at sample code below.
1 class Animal
2 {
3 void eat()
4 {
5 System.out.println(“eating…”);
6 }
7 }
8 class Dog extends Animal
9 {
10 void bark()
11 {
12 System.out.println(“barking…”);
13 }
14 }
15 class Cat extends Animal
16 {
17 void meow()
18 {
19 System.out.println(“meowing…”);
20 }
21
22 public static void main(String args[])
23 {
24 Cat cathy=new Cat();
25 cathy.meow();
26 cathy.eat();
Object-Oriented Programming

27 }
28 }

Thinking Box:
What will be the output of the sample program if line 25 is
removed?

4. MULTIPLE INHERITANCE

public class A
CLASS A CLASS B {
…………
}
public class B
{
…………
CLASS C }
public class C extends A, B
Java does not support multiple {
inheritance. …..
}

Multiple Inheritance refers to the concept of one class extending more


than one classes, which means a child class has two parent classes. For
example class C extends both classes A and B. However, Java doesn’t support
multiple inheritance.
5. HYBRID INHERITANCE public class C
{ …………
}
public class A extends C
{
}
CLASS A CLASS B public class B extends C
{…..
}
public class D extends A
{
………….
}
CLASS D CLASS C

Hybrid inheritance. It is a combination of more than one types of


inheritance in a single program. For example, class A & B extends class C and
another class D extends class A.

A. Evaluate the output of the given code below.


Object-Oriented Programming

1.

class Base {
public void show() {
System.out.println("Base::show() called");
}
}

class Derived extends Base {


public void show() {
System.out.println("Derived::show() called");
}
}

public class Main {


public static void main(String[] args) {
Base b = new Derived();;
b.show();
}
}

2. Assuming that the value of one is 20 and two is 5.


1 import java.io.*;
2 class arithmetic
3 {
4 int one,two,total;
5 String name;
6
7 int sum()
8 {
9 return one+two;
10 }
11
12 void num() throws Exception
13 {
14 DataInputStream in= new DataInputStream
15 (System.in);
16 try{
17 System.out.println("enter two no.:");
18 one=Integer.parseInt(in.readLine());
19 two=Integer.parseInt(in.readLine());
20 }
21 catch (IOException ioe)
22 {
23 System.out.println("invalid input");
24 }
25 }
26
27 public static void main (String []args) throws Exception
28 {
29 arithmetic addition= new arithmetic();
Object-Oriented Programming

30 addition.num();
31 System.out.println("the sum is:"+addition.sum());
32
33 product multiply= new product();
34 multiply.num();
35 System.out.println("the product
36 is:"+multiply.prod());
37 System.out.println("the sum is:"+multiply.sum());
38
39 quotient divide= new quotient();
40 divide.num();
41 System.out.println("the sum is:"+divide.sum());
42 System.out.println("the quotient is:"+divide.quot());
43 System.out.println("the product is:"+divide.prod());
44 }
45 }
46
47 class product extends arithmetic
48 {
49 int prod()
50 {
51 return one*two;
52 }
53 }
54
55 class quotient extends product
56 {
57 int quot()
58 {
59 return one/two;
}
}

B. Determine the type of inheritance program given above and


identify the data members and methods that were being
inherited.

C.

Thinking Box:
What will be the output of the sample program if the method
num is removed?

Recommended Learning Materials and Resources


Object-Oriented Programming

To supplement the lesson in this module, you may visit the following
links:
 http://iiti.ac.in/people/~tanimad/JavaTheCompleteReference.pdf
 http://www.java.sun.com
 www.Callingallinnovators.com

Flexible Teaching Learning Modality (FTLM) adapted


In this lesson, Teaching and learning is mediated through the use of
technology like print, audio, video and the internet. Students interact with
their instructors and each other through virtual classrooms, email, and web
conferencing. For the online modality, the Virtual Classroom shall be used for
the purpose of delivering a lecture and allowing a synchronous discussion
with the students. For the remote modality, Self-directed (SeDI) a learning
management system shall be used to upload the module and to allow
asynchronous discussion with the students. This will also be used as platform
for the submission of the requirements.

ASSESSMENT TASK

A. Evaluate the output of the given code fragments.


1.
Object-Oriented Programming

class Base
{
public void Print()
{
System.out.println("parent");
}
}
class Derived extends Base
{
public void Print()
{
System.out.println("child");
}
}

class Main
{
public static void DoPrint( Base o )
{
o.Print();
}
public static void main(String[] args)
{
Base a = new Base();
Base b = new Derived();
Derived c = new Derived();
DoPrint(a);
DoPrint(b);
DoPrint(c);
}
}

2.
class A
{
{
System.out.println(1);
}
}

class B extends A
{
{
System.out.println(2);
}
}

class C extends B
Object-Oriented Programming

{
{
System.out.println(3);
}
}

public class MainClass


{
public static void main(String[] args)
{
C c = new C();
}
}

3. Determine the output of the program below. Note that fun() is public
Class Parent
in{ base and private in derived.
public void Anak()
{
System.out.println("Base");
}
}
class Child extends Parent
{
private void Anak()
{
System.out.println("Derived");
}
}

public class Main


{
public static void main(String args[])
{
Parent inher = new Child();
inher.Anak();
}
}

B. Examine the code below. Which variable CANNOT be used in the


parent class of Benefit?
public class Benefit
{
private String planCode;
private double HipCode;
Object-Oriented Programming

}
public class health extends Benefit
{
private int coverageOption;
private float employeePremium;
}

C. Provide the correct Inheritance program of each of the items


below given the requirements below.

First Class
 Write a program that will display the employee information such as Full
name, date of birth, age, gender and position.

Second class
 Create a program that will compute the tax of five (5) individual and
display their net income. The computation of the tax is based on the
following:

Civil Status Code Tax (with dependents) Tax (w/out dependents)


1 – Single 10% of Gross Income 15% of Gross Income
2 – Married 5% of Gross Income 9% of Gross Income
3 – Widow/Widower 7% of Gross Income 11% of Gross Income
4 – Separated 8% of Gross Income 12% of Gross Income
Net income is computed as:
Net income = Gross income – Total Deductions
Total deductions = total of the following:
 Tax (refer to the given table)
 Pagibig/Medicare = 320
 SSS = 5% of Gross income

The input shall be the following: civil status code, dependents code (0 – without
dependents / 1 – with dependents), and gross income.
Note: There must be separate methods for the employee information, computation
of tax, pagibig and SSS
: Write a member function to get the employee information in the first class

Third class
 Create a program that will convert a Philippine currency. The program will
assume the following rate of exchange per Philippine Peso. In the case of
other types of currency not listed, the program will just display an error
message.
 D Dollar 44.50
Object-Oriented Programming

 Y Yen 0.58
 R Riyal 18.43
 P Pound 115.65
Note: Please referto the sample below.
Money Changer
Amount 5000
Currency D
Converted 222,500
Note: The net income of the employee in the second class will serves an input in
rate of exchange of Philippine(amount) peso to other currency.
: Write a member function to display the converted peso to currency for
respective salary of the employees.

References

Agarwal , S. & Bansal, H., 2018. Java in Depth. First Edition. ISBN:
9789386551573

Jenkov, J., 2015. Java Inheritance

Savitch, W. J., 2011. Java: An Introduction to Problem Solving and


Programming. ISBN 978-981-0696-66-5

Singh, C., 2020. Beginners Book. Inheritance in Java Programming with


examples.

Vaidya, N.., 2020. Inheritance in Java – Mastering OOP Concepts.

You might also like