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

Chapter 5 - Inheritance

Inheritance allows a subclass to inherit attributes and behaviors from a parent superclass. The subclass can add additional attributes and behaviors while also overriding methods from the superclass. Private members of the superclass cannot be accessed directly by the subclass.

Uploaded by

2022455636
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Chapter 5 - Inheritance

Inheritance allows a subclass to inherit attributes and behaviors from a parent superclass. The subclass can add additional attributes and behaviors while also overriding methods from the superclass. Private members of the superclass cannot be accessed directly by the subclass.

Uploaded by

2022455636
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

CHAPTER 5

Inheritance

By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Science, UiTM
Perlis
Objectives
• By the end of this chapter, students should be able to:
Explore the derivation of new classes (sub classes) from existing ones (superclass).

Define the concept and purpose of method overriding.

Be able to invoke superclass constructors.

Discuss the design of class hierarchies.

Be able to create array of subclass.

Be able to write an application program to implement inheritance concepts.


2
Introduction
(Basic Concepts)
• You are familiar with the concept of inheritance in real life.
Example: Genetic Inheritance

o r Blood type (O+, A)


t e
vi
Saving money
u
ha
Like to eat
i b
Hair type (curly, straight)
tt r
Be
western food
Odd behavior A
Eye color (blue, brown)
(scratching hands
when panic) 3
Introduction
(Basic Concepts)

+
o r u t e
avi r i b
e h
Smoking
A tt
Dress (modern, traditional)
Bshopping w
N ew N e
4
Introduction
(Basic Concepts)
• In OOP, Inheritance is a mechanism
that enables one class to inherit both
attributes and behaviours.
The classes you create can inherit data
and methods from existing classes and
at the same time, you can add extra
data and methods to newly created
classes. 5
Introduction
(Basic Concepts)
y? u
Person
sa o
name
n oy
ca t d

name
ha

studentNumber name
Student Employee employeeNumber
W

Undergraduate Graduate Faculty Staff

Share some common


Master Doctoral attributes and
A class hierarchy behaviors
6
Introduction
• Object-oriented programming allows you to derive new
classes from existing classes called inheritance.

• Inheritance is an important and powerful feature in


Java for reusing software.

• You use a class to model objects of the same type.


Different classes may have some common attributes
and behaviors, which can be generalized in a class
that can be shared by other classes. 7
Introduction
• Inheritance enables you to define a general class and later
extend it to more specialized classes that add some new
details to the existing general class definition.

• The specialized classes inherit the properties/data and methods


from the general class.

• This saves work, because the more specialized class inherits


all the properties of the general class and you need only
program the new features.

8
Inheritance
• Inheritance can be defined as the process of creating new classes
from existing classes by absorbing all their attributes and
behaviors and adding new attributes and behaviors to the newly
created classes.

• The existing class – called super class/base class/parent class.

• The newly created class – called sub class/derived class/child


class.

• The sub class inherits all the attributes (data members) and methods
(method members) of the super class automatically.
9
Inheritance
• The general syntax of deriving a class from a existing class is:
modifier class DerivedClassName extends BaseClassName
{
Declarations_of_Added_Instance_Variables
Definitions_of_Added__And_Changed_Methods
}

• Example: Newly created


Existing class
class

public class Student extends Person


{
//statement;
}
10
Inheritance
(Example)
• The following figure shows the
relationship among these classes.

• An arrow pointing to the superclass is


used to denote the inheritance
relationship between the two classes
involved.
11
Inheritance
(Example)
Person
-name: String super class
+Person()
+Person(String)
+setName(String): void
+getname(): String
+writeOutput(): void sub class
+hasSameName(Person): boolean

Student
New Data
-studentNumber: int
member
+Student()
+Student(String, int)
+reset(String, int): void
+setStudentNumber(int): void
+getStudentNumber(): int
New method +writeOutput(): void
members +equals(Student): boolean
12
Inheritance
(Example)
public class Person
{
private String name;
public Person()
{
name = "No name yet";
}
public Person(String initialName)
{
name = initialName;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
} 13
Inheritance
(Example)
public void writeOutput()
{
System.out.println("Name: " + name);
}
public boolean hasSameName(Person otherPerson)
{
return this.name.equalsIgnoreCase(otherPerson.name);
}
}

14
Inheritance
(Example)
public class Student extends Person
{
private int studentNumber;
public Student()
{
super();
studentNumber = 0;//Indicating no number yet
}
public Student(String initialName, int initialStudentNumber)
{
super(initialName);
studentNumber = initialStudentNumber;
}
public void reset(String newName, int newStudentNumber)
{
setName(newName);
studentNumber = newStudentNumber;
}
15
Inheritance
(Example)
public int getStudentNumber()
{
return studentNumber;
}
public void setStudentNumber(int newStudentNumber)
{
studentNumber = newStudentNumber;
}
public void writeOutput()
{
System.out.println("Name: " + getName());
System.out.println("Student Number: " + studentNumber);
}
public boolean equals(Student otherStudent)
{
return this.hasSameName(otherStudent) &&
(this.studentNumber ==
otherStudent.studentNumber);
}
}
16
Inheritance
(Example)
public class InheritanceDemo
{
public static void main(String[] args)
setName() is inherited from
{ the class Person.
Student s = new Student();
s.setName(“Mus Ali");
s.setStudentNumber(1234);
s.reset(“Mustafa Ali”, 123456);
s.writeOutput();
}
}

Sample of Output:
Name: Mustafa Ali
Student Number: 123456
17
Inheritance
• The following facts about superclass and subclass should be kept in
mind:
The private members of the superclass are private to the superclass; hence, the members of the
subclass cannot directly access them. In another words, when you write the definitions of the methods
of the subclass, you cannot directly access the private members of the superclass.

The subclass can directly access the public members of the superclass.

The subclass can include additional data and/or method members.

The subclass can override, that is, redefine the public method of the superclass. That is, in the
subclass, you can have a method with the same name, number, and types of parameters as a method
in the superclass. However, this redefinition applies only to the object of the subclass, not to the objects
of the superclass.

All data members of the superclass are also data members of the subclass. Similarly, the methods of
the superclass (unless overridden) are also the method of the subclass. 18
Inheritance
• Inheritance can be either single or multiple.

• In single inheritance, the subclass is derived from a single


superclass. We call this relationship an is-a relationship.

Person

Single Inheritance
(Student inherits from Person)
Student

• You should use inheritance only if an is-a relationship exists


between a class and a proposed derived class.
19
Inheritance
• In multiple inheritances, the subclass is derived from
more than one superclass.

Employee Student

Multiple Inheritance
(Staff inherits from Student
Staff and Employee)

• Java ONLY SUPPORT single inheritance.


20
Access Modifier

• Four types of access modifier: private,


protected, public and default.

• The table shows both the accessibility and


inheritability of classes and member
variable from within the same package
and from outside package:
21
Access Modifier
(Access from within class’s Package)

Access Modifier Inherited Accessible


default Yes Yes
public Yes Yes
protected Yes Yes
private No No

22
Access Modifier
(Access from Outside class’s Package)

Access Modifier Inherited Accessible


default No No
public Yes Yes
protected Yes No
private No No

23
Inheritance – Analysis
(private instance variable of a Super
Class)
• private instance variables in a super class are not inherited by a
sub class; they cannot be referenced directly by name within a
derived class.

• Example:
public void reset(String newName, int newStudentNumber)
{
setName(newName); Valid definition
studentNumber = newStudentNumber;
}

public void reset(String newName, int newStudentNumber)


{
name = newName; Invalid definition
studentNumber = newStudentNumber;
}
24
Inheritance – Analysis
(private instance variable of a Super
Class)

CONCEPT
A sub class cannot access the private
instance variables of its base class directly
by name. It knows only about the public
behaviour of the base class.

25
Inheritance – Analysis
(private method of a Super Class)
• A sub class cannot call a private method defined
within the base class.

• However, the sub class can call a public method.


Valid calling method
because setName()
• Example: is a public method

public void reset(String newName, int newStudentNumber)


{
setName(newName);
studentNumber = newStudentNumber;
}
26
Inheritance – Analysis
(private method of a Super Class)

CONCEPT
private methods are not
directly accessible from sub
classes

27
Inheritance – Analysis
(Overriding Method Definition)
• In a sub class, if you include a method definition that has the
same name, the exact same number and types of
parameters, and the same return type as a method already in
the base class, this new definition replaces the old definition of
the method when objects of the derived class receive a call to
the method.

• When overriding a method, you can change the body of the


method definition to anything you wish, but you cannot make
any changes in the method’s heading, including its return
type.
28
Inheritance – Analysis
(Overriding Method Definition)
• Example: the invocation
s.writeOutput();

Will use the method definition of


writeOutput() in the class Student, not
the definition in the class Person, since s is
an object of the class Student.
29
Inheritance – Analysis
(Overriding vs Overloading)
• Do not confuse overriding a method with overloading
a method.
Overriding Overloading

The new method definition The method in the sub class


given in the sub class has has the same name and the
the same name, the same same return type but a different
return type, and the exact number of parameters or a
same number and types of parameter of a different type
parameters from the method from the method in the base
in the base class. class.
30
Inheritance – Analysis
(Overriding vs Overloading)
• Example: Suppose we added the following method to
the definition of the class Student:
ng
public String getName(String title)
di
{
oa d
r l o
return title + getName();
v e th
}
O me
 The class Student would have two methods named getName():
 It would inherit the method getName(), with no parameters, from the base
class, and it would also have the method named getName(), with one
parameter.

 Thus the methods use overloading because the two getName() methods
have different numbers of parameters.
31
Inheritance – Analysis
(The final Modifier)
• If you want to specify that a method definition cannot
be overridden by a new definition within a sub class,
you can add the final modifier to the method
heading.

• Example:

public final void specialMethod()

32
Inheritance – Analysis
(Constructor in Sub Class)
• When defining a constructor for a sub class, you can use
super as a name for the constructor of the base class.

• Any call to super must be the first action taken by the


constructor.

• Example:
public Student(String initialName, int initialStudentNumber)
{
super(initialName);
studentNumber = initialStudentNumber;
}
33
Inheritance – Analysis
(Constructor in Sub Class)
• When you omit a call to the base-class constructor in any sub
class constructor, the default constructor of the base class is
called as the first action in the new constructor.

• Without super, a constructor invokes the default constructor in


the base class

• Example:
public Student() public Student()
{ {
studentNumber = 0; = super();
} studentNumber = 0;
}
34
Inheritance – Analysis
(The this Method)
• Another common action when defining a constructor is to call
another constructor in the same class.
• Example:
In this way, the default
public Person() constructor calls the
{ constructor in the same class
this("No name yet");
}

 When used in a constructor, this public Person(String initialName)


{
calls a constructor of the same name = initialName;
class, but super invokes a }
constructor of the base class.
35
Inheritance – Analysis
(Calling an Overridden Method)
• Within the definition of a method of a sub class, you can call an
overridden method of the base class by prefacing the method
name with super and a dot.

• Syntax:
super.Overridden_Method_Name(Argument_List)

• Example:
Calls writeOutput() in
public void writeOutput() the base/super class
{
super.writeOutput();
System.out.println("Student Number: " + studentNumber);
}
36
Inheritance – Analysis
(Calling Method)
• In general, when writing the definition of the methods of a sub class to
specify a call to a public method of a super class, you do the following:
1
If the sub class overrides a public method of a super class, then
you specify a call to that public method of the superclass by using
the reserved word super followed by dot operator followed by
method name with an appropriate parameter list

2
If the sub class does not override a public method of the super
class, you can specify a call to that public method by using the
name of the method and an appropriate parameter list.

37
Advantages

Software
reusability

Rapid Increased
prototyping reliability

Advantages

Software Code
components sharing

Consistency
of interface

38
Constructing Super Class and Sub Class
(Example 1)
Rectangle
-width: double super class
-length: double
+Rectangle()
+Rectangle(double, double)
+setWidth(double): void sub class
+setLength(double): void
+getWidth(): double
+getLength(): double
+toString():String Box
+calculateArea(): double
+calculatePerimeter(): double -height: double
+Box()
+Box(double,double,double)
+setHeight(double) : void
+getHeight(): double
+toString():String
+calculateVolume(): double
+calculateArea(): double
+calculatePerimeter(): double
39
Constructing Super Class and Sub Class
(Example 1)
//To declare object Rectangle in a file named
//Rectangle.java and put class Rectangle in a package

package shape; //save the file Rectangle.java in package shape

public class Rectangle


{
//attributes
private double width;
private double length;

// default constructor
public Rectangle()
{
width=0;
length=0;
} 40
Constructing Super Class and Sub Class
(Example 1)
//normal constructor
public Rectangle(double width, double length)
{
this.width=width;
this.length=length;
}

//setter or mutator methods


public void setWidth(double w)
{
width=w;
}

public void setLength(double l)


{
length=l;
} 41
Constructing Super Class and Sub Class
(Example 1)
//Getter or accessor methods
public double getLength() {return length;}
public double getWidth() {return width;}

//Printer
public String toString()
{
return “\nThe width:”+width+“\nThe length:”+length;
}

//Processor methods
public double calculateArea()
{
return length*width;
}

public double calculatePerimeter()


{
return (2*length + 2*width);
}
}
42
Constructing Super Class and Sub Class
(Example 1)
//To declare object Box in a file named Box.java
//put class Box in a package
package shape;

//class declaration and definition -use inheritance


public class Box extends Rectangle
{
private double height;

//default constructor
public Box()
{
//implicitly called super OR you can write super()
height=0;
}

43
Constructing Super Class and Sub Class
(Example 1)
//normal constructor
public Box(double width, double length, double height)
{
super(width, length);
this.height=height;
}

//setter or mutator methods


public void setHeight(double h)
{
height=h;
}

//getter or accessor methods


public double getHeight(){return height;} 44
Constructing Super Class and Sub Class
(Example 1)
//Printer
public String toString()
{
return super.toString()+ “\nThe
height:”+height;
}

//Processor methods
public double calculateVolume()
{
return (getLength()*getWidth()*height);
}

45
Constructing Super Class and Sub Class
(Example 1)
public double calculateArea()
{
return ( 2*(getLength()*getWidth())+ 2*(height
*getWidth()) + 2*(getLength()*height));
}

public double calculatePerimeter()


{
return (4*getLength()+4*getWidth()+4*height);
}
}

46
Constructing Super Class and Sub Class
(Example 1)
/*To declare Java application program in a file named
TestingInheritance.java*/
import shape.*;
import java.util.*;

public class TestingInheritance


{
public static void main(String[] args)
{
Scanner scanner = new Scanner (System.in);
Box b = new Box();

//input data
System.out.print("Input the width:");
double width = scanner.nextDouble();
System.out.print(“Input the lenght:");
double length = scanner.nextDouble();
System.out.print(“Input the height:");
double height = scanner.nextDouble();
47
Constructing Super Class and Sub Class
(Example 1)
//Setting the data into an object of class Box using Mutator
b.setWidth(width);
b.setLength(length);
b.setHeight(height);

System.out.println(b.toString());
System.out.println("The area :" +b.calculateArea());
System.out.println("The perimeter :"+ b.calculatePerimeter());
System.out.println("The volume :"+b.calculateVolume());
System.exit(0);
Sample of Output:
}
Input the width: 3.0
}
Input the length: 2.5
Input the height: 2.0
The width : 3.0
The length :2.5
The height : 2.0
The area : 34.0
The perimeter : 30.0
48
The volume : 15.0
Constructing Super Class and Sub Class
(Example 1)
//OR Setting the data into an object of class Box using
//normal constructor
b = new Box(width, length, height);

System.out.println(b.toString());
System.out.println("The area :" +b.calculateArea());
System.out.println("The perimeter :"+ b.calculatePerimeter());
System.out.println("The volume :"+b.calculateVolume());
System.exit(0);
Sample of Output:
}
Input the width: 3.0
}
Input the length: 2.5
Input the height: 2.0
The width : 3.0
The length :2.5
The height : 2.0
The area : 34.0
The perimeter : 30.0
The volume : 15.0
49
Constructing Super Class and Sub Class
(Example 2)
Worker
super class
-workerNum: int
-workerName: String
-position: String
+Worker()
+Worker(int, String,String) sub class
+setWorker Num(int): void
+setWorkerName(String): void
+setPosition(String): void PermanentWorker
+toString(): String
-basicSalary: double
-allowance: double
+PermanentWorker()
+PermanentWorker(int,String,String,
double, double)
+setBasicSalary(double) : void
+setAllowance(double):
50void
+calculateMonthlySalary(): double
+toString(): String
Constructing Super Class and Sub Class
(Example 2)
public class Worker
{
private int workerNum;
private String workerName;
private String position;

public Worker() //Default Constructor


{
workerNum = 0;
workerName = "";
position = "";
}

public Worker(int wNum, String wNm, String pos)//Normal Constructor


{
workerNum = wNum;
workerName = wNm;
position = pos;
}

51
Constructing Super Class and Sub Class
(Example 2)
public void setWorkerNum(int wNum) //Setter
{
workerNum = wNum;
}

public void setWorkerName(String wNm) //Setter


{
workerName = wNm;
}

public void setPosition(String pos) //Setter


{
position = pos;
}

public String toString()//Printer


{
return “\nWorker Number: " +workerNum +“\nWorker Name: " +
workerName+ “\nWorker Position: " +position;
}
}
52
Constructing Super Class and Sub Class
(Example 2)
public class PermanentWorker extends Worker
{
private double basicSalary;
private double allowance;

public PermanentWorker()//Default Constructor


{
super();
basicSalary = 0.0;
allowance = 0.0;
}

//Normal Constructor
public PermanentWorker(int wNum, String wNm, String pos, double bs, double al)
{
super(wNum, wNm, pos);
basicSalary = bs;
allowance = al;
}

public void setBasicSalary(double bs)//Setter


{
basicSalary = bs;
53
}
Constructing Super Class and Sub Class
(Example 2)
public void setAllowance(double al) //Setter
{
allowance = al
}

public double calculateMonthlySalary() //Processor


{
return basicSalary + allowance;
}

public String toString() //Printer


{
return super.toString()+ “\nBasic Salary: " +
basicSalary+ “\nAllowance: " +allowance;
}
}
54
Constructing Super Class and Sub Class
(Example 2)
import java.util.*;
public class AppWorker
{
public static void main(String args[])
{
Scanner scanner = new Scanner (System.in);

for(int i = 0; i<10; i++)


{
System.out.print(“Enter worker number: ");
int wNum = scanner.nextInt();
System.out.print("Enter worker name: ");
String wNm = scanner.next();
System.out.print("Enter position: ");
String pos = scanner.next();
System.out.print(("Enter basic salary: ");
double bs = scanner.nextDouble();
System.out.print("Enter allowance: ");
double a = scanner.nextDouble(); 55
Constructing Super Class and Sub Class
(Example 2)
PermanentWorker pw = new PermanentWorker();
Do we have some
//Input using mutator
pw.setWorkerNum(wNum);
problems here?
pw.setWorkerName(wNm); • Can we have
pw.setPosition(pos); other processes
pw.setBasicSalary(bs);
outside the loop
pw.setAllowance(a);
control structure
double salary = pw.calculateMonthlySalary();
System.out.println(pw.toString()+ “Salary: RM” + salary);
}
System.exit(0);
}
}

56
Constructing Super Class and Sub Class
(Example 2)
//Input using normal constructor
PermanentWorker pw = new PermanentWorker(Wnum,WNm,pos,bs,a);

double salary = pw.calculateMonthlySalary();


System.out.println(pw.toString()+ “Salary: RM” + salary);
}
System.exit(0);
} Do we have some
} problems here?
• Can we have
other processes
outside the loop
control structure

57
Constructing Super Class and Sub Class
(Array of Sub Class – based on Example 2)
import java.util.*;
public class AppWorker
{
public static void main(String args[])
{
Scanner scanner = new Scanner (System.in);
PermanentWorker[] pw = new PermanentWorker[10];//STEP 1: Array Declaration

for(int i = 0; i<10; i++) //STEP 2: Instantiate array of objects


pw[i] = new PermanentWorker();

for(int i = 0; i<10; i++) //STEP 3: Input Process


{
System.out.print(“Enter worker number: ");
int wNum = scanner.nextInt();
System.out.print("Enter worker name: ");
String wNm = scanner.next();
System.out.print("Enter position: ");
String pos = scanner.next();
System.out.print(("Enter basic salary: ");
double bs = scanner.nextDouble();
System.out.print("Enter allowance: "); 58
double a = scanner.nextDouble();
Constructing Super Class and Sub Class
(Array of Sub Class – based on Example 2)
//STEP 4: Store onto object
//Store onto object using mutator
pw[i].setWorkerNum(wNum);
pw[i].setWorkerName(wNm);
pw[i].setPosition(pos);
pw[i].setBasicSalary(bs);
pw[i].setAllowance(a);
}

for(int i =0; i<10; i++)//STEP 5: Manipulation


{
double salary = pw[i].calculateMonthlySalary();
System.out.println(pw[i].toString()+ “Monthly salary:”
+salary);
}
System.exit(0);
}
}
59
Constructing Super Class and Sub Class
(Array of Sub Class – based on Example 2)
//STEP 4: Store onto object
// OR Store onto object using Normal Constructor
pw[i] = new PermanentWorker(wNum,wNm,pos,bs,a);
}

for(int i =0; i<10; i++)//Manipulation


{
double salary = pw[i].calculateMonthlySalary();
System.out.println(pw[i].toString()+ “Monthly salary:”
+salary);
}
System.exit(0);
}
}

60
Object of Super Class and Sub
Class
• Java allows us to treat an object of a sub class
as an object of its super class. In another
words, a reference variable of a super class
type can point to an object of its subclass.

• Moreover, by using an appropriate cast


operator, you can treat an object of a
superclass type as an object of a superclass
61
Object of Super Class and Sub
Class
• An object of a sub class has the type of the sub
class, but it can be referenced by a variable
whose type is any one of its ancestor classes.

• Thus, you can assign an object of a sub class


to a variable of any ancestor type, BUT not the
other way around.

62
Inheritance
(Type Compatibility)
Suppose we define class Undergraduate
Inherited from Student
public class Undergraduate extends Student
{
private int level;

//method members

public boolean equals(Undergraduate un)


{
return equals((Student)un) &&
(this.level == un.level));
}
}

63
Inheritance
(Type Compatibility)
• The following code is valid
Student s = new Student();
Undergraduate ug = new Undergraduate();
Person p1 = s;
Person p2 = ug;

• You can even bypass the variables s and ug and


place the new objects directly into the variables p1
and p2, as follows:
Person p1 = new Student();
Person p2 = new Undergraduate();
64
Inheritance
(Type Compatibility)
• However, the following statements are all illegal:
Student s = new Person(); //ILLEGAL!
Undergraduate ug = new Person(); //ILLEGAL!
Undergraduate ug2 = new Student(); //ILLEGAL!

• And if we define p and s as follows:


Person p = new Person(); //valid
Student s = new Student(); //valid

• Even the following statements, which may look more innocent, are similarly
illegal:
Undergraduate ug = p; //ILLEGAL!
Undergraduate ug2 = s; //ILLEGAL!

65
The Operator instanceof
• To determine whether a reference variable that points
to an object is of a particular class type, Java provides
the operator instanceof.

• Example:
p instanceof Rectangle

 This expression evaluates to true if p points to an object of


the class Rectangle; otherwise it evaluates to false.

66
The Operator instanceof
(Example 1)
TwoD

-area: double
-perimeter: double
Super class
+TwoD()
+getArea(): double
+getPerimeter(): double
+calculateArea(): void
+calculatePerimeter(): void
+toString(): String

Rectangle

Circle -width: double


-length: double
-radius: double
+Rectangle()
+Circle() +setWidth(double): void
+setRadius(double): void +setLength(double): void
+calculateArea(): void +getWidth(): 67
double
+calculatePerimeter(): void +getLength(): double
Sub class +calculateArea(): void
+toString(): String
+calculatePerimeter(): void
+toString(): String
The Operator instanceof
(Example 1)
//Put class TwoD in a package
package twoD;

//Class declaration and definition


public class TwoD
{
protected double area;
protected double perimeter;

//Constructor
public TwoD()
{
area=0;
perimeter=0;
}
//Getter or mutator methods
public double getArea(){return area;}
public double getPerimeter(){return perimeter;}
68
The Operator instanceof
(Example 1)
//Processor methods
public void calculateArea()
{
area = 0.0;
}

public void calculatePerimeter()


{
perimeter = 0;
}

public String toString()


{
return “\nArea : " +area+ "\n" +“Perimeter :"
+perimeter;
}
}

69
The Operator instanceof
(Example 1)
//Put class Rectangle in a package
package twoD;

//class declaration and definition


public class Rectangle extends TwoD
{
private double width;
private double length;

//constructor
public Rectangle()
{
super();
width=0;
length=0;
}
70
The Operator instanceof
(Example 1)
//setter methods
public void setWidth(double w)
{
width=w;
}

public void setLength(double l)


{
length=l;
}

//getter methods
public double getLength(){return length;}
public double getWidth(){return width;}
//processor methods
public void calculateArea()
{ 71
area=length*width;
The Operator instanceof
(Example 1)
public void calculatePerimeter()
{
perimeter=2*length+2*width;
}

//printer methods
public String toString()
{
String result;
result ="";
String line1,line2,line3,line4,line;
line = "RECTANGLE:" + "\n";
line1 = "The width : " +width+ "\n";
line2 = "The length : " +length+ "\n";
line3 = "The area : " +area+ "\n";
line4 = "The perimeter: " +perimeter+ "\n";
result = line+line1+line2+line3+line4;
return result;
} 72
}
The Operator instanceof
(Example 1)
//put class circle in a package
package twoD;

//Class declaration and definition


public class Circle extends TwoD
{
private double radius;

//constructor
public Circle()
{
super();
radius=0;
}

//setter methods
public void setRadius(double r)
{
radius=r;
}

73
The Operator instanceof
(Example 1)
//getter methods
public void calculateArea()
{
area=Math.PI*Math.pow(radius,2);
}

public void calculatePerimeter()


{
perimeter=2*Math.PI*radius;
}

74
The Operator instanceof
(Example 1)
//printer methods
public String toString()
{
//Formating
DecimalFormat dF= new DecimalFormat("0.00");

String result;
//initialize result
result="";
String line1,line2,line3,line;
line = "CIRCLE: " + "\n";
line1 = "The width : " +radius+ "\n";
line2 = "The area : " +dF.format(area)+ "\n";
line3 = "The perimeter : " +dF.format(perimeter)+ "\n";
result = line+line1+line2+line3;

return result;
}
} 75
The Operator instanceof
(Example 1)
import twoD.TwoD;
import twoD.Rectangle;
import twoD.Circle;

import javax.swing.JOptionPane;

public class TestingTwoD


{
public static void main(String[] args)
{
//STEP 1: Declare an array of TwoD (Superclass)
TwoD[] td = new TwoD[5];

STEP 2: Instantiate array of objects


for(int i=0; i<5; i++)
td[i] = new TwoD();
76
The Operator instanceof
(Example 1)
//STEP 3: Input
for(int i=0; i<5; i++)
{
//display menu 1-rectangle 2-circle
String strChoice = JOptionPane.showInputDialog(
"Your choice?(1/2)");
//convert to integer
int c = Integer.parseInt(strChoice);

if(c==1)
{
Rectangle rec = new Rectangle();

//input number as strings


String strWidth = JOptionPane.showInputDialog(
"Input the width :");
String strLen = JOptionPane.showInputDialog(
"Input the length :");

//convert strings into numbers


double w = Double.parseDouble(strWidth);
double l = Double.parseDouble(strLen); 77
The Operator instanceof
(Example 1)
//convert strings into numbers
double w = Double.parseDouble(strWidth);
double l = Double.parseDouble(strLen);

//Setting the data into an object


rec.setWidth(w);
rec.setLength(l);

//calculation
rec.calculateArea();
rec.calculatePerimeter();

//STEP 4: Store onto object of superclass


td[i] = rec;
}

78
The Operator instanceof
(Example 1)
else
{
Circle cir = new Circle();
//input number as string
String strRadius = JOptionPane.showInputDialog(
"Input the radius :");

//convert string into numbers


double r = Double.parseDouble(strRadius);

//setting the data into an object


cir.setRadius(r);

//Calculation
cir.calculateArea();
cir.calculatePerimeter();

//STEP 4: Store onto object of superclass


td[i]=cir;
}
}
79
The Operator instanceof
(Example 1)
//STEP 5: Manipulation
//to display - notice that we use the same method name
//for all classes
for(int j=0;j<td.length;j++)
{
JOptionPane.showMessageDialog(null,td[j].toString());
}

//to display and count only for circle


int cntCircle = 0;
String output = “”;
for(int i=0; i<td.length; i++){
if(td[i] instanceof Circle){
output += td[i].toString()+"\n";
cntCircle = cntCircle + 1;
}
} 80
The Operator instanceof
(Example 1)
JOptionPane.showMessageDialog(null, "Total of circle: "
+ cntCircle);
JOptionPane.showMessageDialog(null, "Information Of
circle: " +"\n"+ output);

System.exit(0);
}
}

81
The Operator instanceof
(Example 2)
RegularService
Customer -numVoiceSms: int
-name: String
-address: String +RegularService()
-telephoneNo: String +RegularService(String,String,String,int,double,boolean, int)
-noOfSms: int +setNumVoiceSms(int): void
-minuteCall: double +getNumVoiceSms(int): int
-threeG: boolean +calcCharge(): double
+toString(): String
+Customer()
+Customer(String,String,String,int,double,boolean)
+setName(String): void
+setAddress(String): void
PremiumService
+setTelephoneNo(String): void
+setNoOfSms(int): void -minutesVideoCall: double
+setMinuteCall(double): void -minutesVideoMail: double
+setThreeG(boolean): void
+getName(): String +PremiumService()
+getAddress(String): String +PremiumService(String,String,String,int,double,boolean,
+getTelephoneNo(String): String double,double)
+getNoOfSms(int): int +setMinutesVideoCall(double): void
+getMinuteCall(double): double +setVideoMail(double): void
+getThreeG(boolean): boolean +getMinutesVideoCall(): double
+getVideoMail(): double
82
+toString(): String
+calcCharge(): double
+toString(): String

Super class
Sub class
The Operator instanceof
(Example 2)
public class Customer{
private String name;
private String address;
private String telephoneNo;
private int noOfSms;
private double minuteCall;
private boolean threeG;

//Default Constructor
public Customer()
{
name = “”;
address = “”;
telephoneNo = “”;
noOfSms = 0;
minuteCall = 0.0;
threeG = false;
}
The Operator instanceof
(Example 2)
//Normal Constructor
public Customer(String nm, String ad, String tn, int ns,
double mc, boolean tg)
{
name = nm;
address = ad;
telephoneNo = tn;
noOfSms = ns;
minuteCall = mc;
threeG = tg;
}

//Mutator
public void setName(String nm) { name = nm; }
public void setAddress(String ad) { address = ad; }
public void setTelephoneNo(String tn) {telephoneNo = tn;}
public void setNoOfSms(int ns) { noOfSms = ns; }
public void setMinuteCall(double mc) { minuteCall = mc; }
public void setThreeG(boolean tg) { threeG = tg; }
The Operator instanceof
(Example 2)
//Accessor
public String getName() { return name; }
public String getAddress() { return address; }
public String getTelephoneNo() { return telephoneNo; }
public int getNoOfSms() { return noOfSms; }
public double getMinuteCall() { return minuteCall; }
public boolean setThreeG() { return threeG; }

//Printer
public String toString()
{
return “\nName:”+name+ “\nAddress:”+address
+ “\nTelephone:”+telephoneNo+ “\nNo. of SMS:”
+noOfSms+ “\nMinute Call:”+minuteCall
+ “\nThree G:”+threeG;
}
}
The Operator instanceof
(Example 2)
public class RegularService extends Customer {
private int numVoiceSms;

//Default Constructor
public RegularService()
{
super();
numVoiceSms = 0;
}

//Normal Constructor
public RegularService(String nm, String ad, String tn,
int ns, double mc, boolean tg, int nv)
{ super(nm, ad, tn, ns, mc, tg);
numVoiceSms = nv;
}

//Mutator
public void setNumVoiceSms(int nv)
{ numVoiceSms = nv; }
The Operator instanceof
(Example 2)
//Accessor
public int getNumVoiceSms()
{ return numVoiceSms; }

//Processor
public double calcCharge()
{
double totCharge = getMinuteCall() * 0.20 +
getNoOfSms()* 0.05 + numVoiceSms*0.50;

return totCharge;
}

//Printer
public String toString()
{
return super.toString()+ “\nNum. voice SMS:” +numVoiceSms;
}
}
The Operator instanceof
(Example 2)
public class PremiumService extends Customer {
private double minutesVideoCall;
private double minutesVideoMail;

//Default Constructor
public PremiumService()
{ super();
minutesVideoCall = 0.0;
minutesVideoMail = 0.0;
}

//Normal Constructor
public PremiumService(String nm, String ad, String tn,
int ns, double mc, boolean tg, int mvc, int mvm)
{
super(nm, ad, tn, ns, mc, tg);
minutesVideoCall = mvc;
minutesVideoMail = mvm;
}
The Operator instanceof
(Example 2)
//Mutator
public void setMinutesVideoCall(double mvc)
{ minutesVideoCall = mvc; }

public void setMinutesVideoMail(double mvm)


{ minutesVideoMail = mvm; }

//Accessor
public double getMinutesVideoCall()
{ return minutesVideoCall; }

public double getMinutesVideoMail()


{ return minutesVideoMail; }
The Operator instanceof
(Example 2)
//Processor
public double calcCharge()
{
double totCharge = getMinuteCall() * 0.20 +
getNoOfSms()* 0.05 + minutesVideoCall * 1.00 +
minutesVideoMail * 0.80;

return totCharge;
}

//Printer
public String toString()
{
return super.toString()+ “\nMinutes video call:”
+minutesVideoCall+ “\nMinutes video mail:”
+minutesVideoMail;
}
}
The Operator instanceof
(Example 2)
import java.util.*;
public class CustomerApp{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);

//STEP 1:Declare array of object using super class


System.out.println(“Enter saiz of array:”);
int size = scan.nextInt();
Customer[] cus = new Customer[size];

//STEP 2: Instantiate array of object


for (int i=0; i<size; i++)
cus[i] = new Customer();
The Operator instanceof
(Example 2)
//STEP 3: Input
for (int i=0; i<size; i++){
//Input for general
System.out.print(“Enter name:”);
String nm = scan.nextLine();
System.out.print(“Enter address:”);
String ad = scan.nextLine();
System.out.print(“Enter telephone no:”);
String tn = scan.nextLine();
System.out.print(“Enter no. of sms:”);
int ns = scan.nextInt();
System.out.print(“Enter minute call:”);
double mc = scan.nextDouble();
System.out.print(“Enter three G:”);
boolean tg = scan.nextBoolean();
//asking for specific object [1- Regular Service
//or 2- Premium Service]
System.out.print(“Enter your choice[1- Regular
Service or 2- Premium Service]:”);
int choice = scan.nextInt();
The Operator instanceof
(Example 2)
if(choice == 1){
//Input for specific object – RegularService
System.out.print(“Enter no of voice sms:”);
int nv = scan.nextInt();
//STEP 4: Store onto object using normal constructor
cus[i] = new RegularService(nm,ad,tn,ns,mc,
tg,nv);
}
else{
//Input for specific object – PremiumService
System.out.print(“Enter minute video call:”);
double mvc = scan.nextDouble();
System.out.print(“Enter minute video mail:”);
double mvm = scan.nextDouble();
//STEP 4: store onto object using normal constructor
cus[i] = new PremiumService(nm,ad,tn,ns,mc,tg,
mvc, mvm);
}
}//end for
The Operator instanceof
(Example 2)
//STEP 5: Manipulation
//Calculate and display the total amount of charge for
//all regular service and premium service.
double totChgRegular = 0.0;
double totChgPremium = 0.0;
for(int i=0; i<size; i++){
if(cus[i] instanceof RegularService){
RegularService rs = (RegularService) cus[i];
totChgRegular += rs.calcCharge();
}
else{
PremiumService ps = (PremiumService) cus[i];
totChgPremium += ps.calcCharge();
}
}
System.out.println(“Total Charge Regular: RM”+totChgRegular);
System.out.println(“Total Charge Premium: RM”+totChgPremium);
The Operator instanceof
(Example 2)
//Calculate and display the number of customers and
//the highest charges for those who make a video call.
int cntCus = 0;
double maxCharge = 0.0;
PremiumService maxObj = null;
for(int i=0; i<size; i++){
if (cus[i] instanceof PremiumService){
PremiumService ps = (PremiumService) cus[i];
cntCus++;
if(ps.calcCharge() > maxCharge)
{
maxCharge = ps.calcCharge();
maxObj = ps;
}
}
}
System.out.println(“The total customer:”+cntCus);
System.out.println(“The highest charge for
customer:”+maxObj.toString()+ “ with RM:”+maxCharge);
The Operator instanceof
(Example 2)
//Display all information of customers who get the
//service of voice SMS.
for(int i=0; i<size; i++){
if (cus[i] instanceof RegularService)
System.out.println(cus[i].toString());
}
}//end main
}//end class
The object Class
• In Java, every class is derived from the class Object.

• The class Object is the ultimate ancestor of all classes

• Every classes that you define yourself without using inheritance are descendant
classes of the class Object. If you do not make your class a derived class of
some class, Java will automatically make it a derived class of Object.

• Example:

extends Object {
public class Employee {
data members;
method members;
}
97
The object Class
• The class Object allows Java programmers to write Java
methods that have a parameter of type Object that
represents an object of any class.

• The class Object does have some methods that every Java
class inherits

• Every class inherits the methods toString() and


equals() from Object.
 However, it will not work correctly for almost any class you define.
Thus, you need to override the inherited method definitions with
new, more appropriate definitions. 98
The End
Q&A
99

You might also like