Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

CHAPTER 1 : INTRODUCTION TO OBJECT ORIENTED

PROGRAMMING

Learning Outcomes
At the end of learning, student should be able to:
 Write a Java basic programming
 Describe the concept of OOP
 Write the attribute and behaviour of object
 List the characteristics of OOP

Programming Basics

Data type in Java


There two types of data type
i. Primitive
ii. Non-Primitive
Data types

Primitve data type Non-primitve data type


- byte - Array
- short - String
- int - class
- long - etc
- float
- double
- char
- boolean

Primitive means the most basic data type available within the Java langauge. As usual, all
variables must be declared.

Example of variable declaration :

int number1, number2;


double number1, number2;
char code;
String name;
Boolean answer;

Java is case sensitive, lower case and upper case letter are represented differently.

Example :
String name, Name;

Input data
There are two(2) ways to input data in Java

1
i. Using Dialog box
Example:

String name=JOptionPane.showInputDialog("Insert name:");


String sal =JOptionPane.showInputDialog(“Insert salary:”);
double salary = Double.parse.Double(sal);

ii. Using object of Scanner class


Example:
//create an object named input of Scanner
Scanner input = new Scanner(System.in);

System.out.println ("Enter Student ID = ");


int id = input.nextInt(); //take input from the user
System.out.println ("Enter Student Mark = ");
double mark = input.nextDouble();//take input from the user

Note :
For dialog box, need to import : import javax.swing.*;
For Scanner class, need to import : import java.util.Scanner;

All data inserted in Java is in the String data type. So for numbering data, we need to
convert into primitive data type as given example above.

Java Output
Send data to output screen :
i. Using System.out.println() or System.out.print() :

Example:
System.out.println(“1. Good Morning “);
System.out.println(“2. Good Afternoon ”);
System.out.print(1. Good Morning ”);
System.out.print(2. Good Afteroon”);

Output:
1. Good Morning
2. Good Afternoon
1. Good Morning 2. Good Afternoon

ii. Using message dialog


Example:
JOptionPane.showMessageDialog(null,”The sum of 1 and
2 is 3”);

Output:
The sum of 1 and 2 is 3

2
Control Structure
i. Sequence
ii. Selection
iii. Repetition

Sequence

//to calculate the total of one year salary


import javax.swing.*;
public class employApp
{
public static void main(String [] args)
{
double salaryInYear;
String name=JOptionPane.showInputDialog("Insert name:");
String icNumber = JOptionPane.showInputDialog("Insert ic
number :");

String sal = JOptionPane.showInputDialog ("Insert salary


per month :");
double salary = Double.parseDouble(sal);

salaryInYear = salary * 12;


System.out.println("Employee Name : "+name);
System.out.println("IC Number : "+icNumber);
System.out.println("Salary per month : "+salary);
System.out.println("Total salary in a year : "
+salaryInYear);
}
}

3
Selection
//to find the maximum value between two numbers
import javax.swing.*;
public class MaxApp {
public static void main(String [] args)
{ int number1, number2, maximum;
String num1=JOptionPane.showInputDialog("Enter number1: ");
String num2=JOptionPane.showInputDialog("Enter number 2:");

number1 = Integer.parseInt(num1);
number2 = Integer.parseInt(num2);

if(number1 > number2)


maximum = number1;
else
maximum = number2;

System.out.println("Number 1 : "+number1);
System.out.println("Number 2 : "+number2);
System.out.println("Maximum number is : "+maximum);
}
}

4
Repetition

import javax.swing.*;
import java.util.Scanner;
public class repeatApp
{
public static void main(String []args)
{ int id;
double mark;
char grade;

Scanner scan = new Scanner(System.in);


for(int i=0; i<2; i++)
{
System.out.println ("Student "+(i+1));
System.out.println ("Enter Student ID = ");
id = scan.nextInt();
System.out.println ("Enter Student Mark = ");
mark = scan.nextDouble();

if(mark>=80)
grade = 'A';
else if (mark >=70)
grade = 'B';
else if (mark >=60)
grade = 'C';
else if (mark >=50)
grade = 'D';
else
grade = 'F';

System.out.println("Grade : "+grade+"\n");
}
} }

Output:
Student 1
Enter Student ID =
111
Enter Student Mark =
80
Grade : A

Student 2
Enter Student ID =
123
Enter Student Mark =
67
Grade : C

5
Program with Array

import javax.swing.*;
import java.util.Scanner;
public class arayApp
{
public static void main(String []args)
{
int id[] = new int[2];
double mark[] = new double[2];
char grade[] = new char[2];

Scanner scan = new Scanner(System.in);

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


{
System.out.println ("Enter Student ID = ");
id[i] = scan.nextInt();
System.out.println ("Enter Student Mark = ");
mark[i] = scan.nextDouble();
}

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


{
if(mark[i]>=80)
grade[i] = 'A';
else if (mark[i] >=70)
grade[i] = 'B';
else if (mark[i] >=60)
grade[i] = 'C';
else if (mark[i] >=50)
grade[i] = 'D';
else
grade[i] = 'F';
}

6
System.out.println("=============");
for(int i=0; i<2; i++)
{
System.out.println("Student ID : "+id[i]);
System.out.println("Mark : "+mark[i]);
System.out.println("Grade : "+grade[i]);
}

int indexFound=0;
boolean found = false;
for(int i=0; i<2; i++)
{
if(id[i] == 123)
{ found = true;
indexFound = i;
}
}

if(found)
{ System.out.println("Mark and Grade with the Student
ID 123 is: ");
System.out.println("====> "+mark[indexFound]+" :
"+grade[indexFound]);
}
else
System.out.println("Data for Student ID 123 is not
found ");
}
}

Output:
Enter Student ID =
123
Enter Student Mark =
80
Enter Student ID =
111
Enter Student Mark =
78
=============
Student ID : 123
Mark : 80.0
Grade : A
Student ID : 111
Mark : 78.0
Grade : B
Mark and Grade with the Student ID 123 is :
====> 80.0 : A

7
Exercise:

1. Write a Java program that can assign and display all the code to the menu package
respectively.
Each code indicates the following menu package :
Code Package
A Standard
B Deluxe
C Family

2. Given the following program :

import javax.swing.*;
import java.text.*;
public class circleApp
{
public static void main()
{
final double PI = 3.14159; //constant value
double radius,rad, circumference;

DecimalFormat df = new DecimalFormat("0.0");

rad=JOptionPane.showInputDialog("Insert radius : "));


radius = Double.parseDouble(rad);
circumference = 2 * PI * radius;
System.out.println("Radius :"+radius);

System.out.println("Circumference :"+df.format(circu
mference));
}
}

What is the output of the above program?

3. Write a program that can read parking hours of MyShop parking lot. Calculate the
charge of parking hours as follows:
- Less than one hour, no charges
- one to four hours, RM1.00.
- More than four hours, for every hour will be charge RM0.50.

Introduction to Object and Class

Imagine a set of instruction or recipe to make a Bun. We can’t eat the recipe of Bun, but we
can eat Bun. To make a Bun, we need to follow the instruction correctly. So, the Bun is an
object made of the recipe. We can make many Buns. We can make another two Buns for
mum and dad using the same recipe.

8
Before we implement any recipe, we need to assign what objects involved. Objects are
representations of real things that we can imagine, tangible and intangible.

For example, in Figure 1.4 (Chapter 1), we have four students. Each student is an object. So
there are four objects.

OOP is a programming styles that using object as a model of the concept or process. Every
object contains properties/data members and methods. Properties mean something that tells
about the object. What we need to know about the object. Example, properties for an object
person is name, age, height and weight.

For the living object, methods are something that objects can do (process/procedure/set of
instruction). Method for person are talk, walk, run, eat and so on. For the non-living object,
method is what we can do to the object. Example method for rectangle is we can calculate the
area and volume of rectangle. The collection of objects of similar type is called a class. A
class is like a recipe for Bun. From the recipe, we can make many Buns (objects).
Class can be defined as a template/blueprint that describes the data members and behavior of
the object. Method is a behavior. A class can contain many methods. It is in methods where
the logics are written, data is manipulated and all the actions are executed.

Elements of object
i. Data member/Attribute/Properties

An attribute is also known as field or variable. It can be accessed directly. It's typically a
public constant or a public variable.

For example: Attributes for object car are name, colour, engineType

ii. Behaviour

Behaviour refers to an object’s function or method. It refers to how object interact with each
other. For example: Behaviour of object car is moving, breaking.

CD player is an object. The behaviour of CD player maybe Play, Pause, Reverse,


Eject and so on.

There are millions of such cars in the world. Therefore, we can identify a class of Cars. A
particular car is an object which is an instance of a class Cars. An instance is a specific object
built from a specific class.

Example: Elements of Object

a.

Object Cat
Attributes name, colour, age
Behaviour meowing, sleeping, grooming,
eating

9
b.

Object Student
Attributes name, age, ic number, gender
Behaviour register, calculate fee

c.

Object Bank customer


Attributes name, age, ic number, address,
marital status, tel_no
Behaviour register, calculate loan,

iii. State

Every object has a state or value. We can say that the state is the conditions in which objects
exist. An object's state is defined by its attributes. An object's attributes are usually static (fix),
but the values of the attributes are usually dynamic (can be change).

Object Cat
Attributes Name = “Comel”
Colour = “White”
Age = 1 year
Behaviour meowing, sleeping, grooming,
eating

Name, Colour and Age are attributes meanwhile Comel, White and 1 are states/values of
the attributes and they can be change to other values.
For example: the state of attribute Name can be changed from “Comel” to “Intan"

10
Example 1:
The program below is an example of how to declare attributes and methods of object
Employee using Java program. The class named Employee is as a template.

public class Employee


{
private String name;
private int icNumber;
private double salaryPerMonth;

public inputData()
{
name = “Ahmad”;
icNumber = 645512347878;
salaryPerMonth= 3400.00;
}

public double computeSalaryPerYear()


{
System.out.println("Salary for a year");
double salaryPerYear = salaryPerMonth * 12;
return salaryPerYear;
}

public String Display()


{
return name + " " + icNumber+ " "+salaryPerMonth +
" "+computeSalaryPerYear();
}

From the example above, it shows that the object named Employee has specific value.
Object Employee
Attributes name = Ahmad
ic_number = 645512347878
salary per month = 3400.00
Behaviour inputData, computeSalaryPerYear,Display

The state of Employee is “Ahmad” for name, 645512347878 for ic number and
3400.00 for salary Pe rMonth.

11
Exercise:
1. What is OOP?
2. List the attributes and behaviour for each of the following objects:
i. Book
ii. File
iii. Computer
iv. Vegetable
3. You are assigned to describe a flower for Java class definition.
i. Identify the most appropriate class name.
ii. List THREE (3) relevant attributes.

Characteristic of OOP

i. Abstraction

Abstraction means that we only focusing on the essential features of an object that distinguish
it from other objects and ignoring unrelated features between objects.

Example:

public class Student


{
private String name;
private int icNumber;
private String course;
private String address;
private double bodySize, sizeRetina, rateOfPulse;

public void register(String course)


{ ……… }

public void drop(String course)


{ …….. }
}

In a class Student where the essential characteristics like name, ic number,


course, and address are included while other characteristics like size_of_body,
size_of_retina and rate_of_pulse are eliminated because they are irrelevant in
the perspective of the educational institution.

Abstraction also can be explained as a process of hiding implementation details from the user.
Only the signature of function header will be provided to the user. It is required to separate
class definition from the use of the class. To meet this purpose, we need to define a class
application and class definition. Class definition contains all data and methods required to
create a class. Example is class Student as mentioned above. Class application will use the
defined class as an example below:

12
public class StudentApp
{
public static void main(String args[])
{
Student s1, s2;
s1.register(“CSC186”);
s1.drop(“CSC238”);
s2.register(“CSC118”);
}
}

ii. Encapsulation
Encapsulation is the process of wrapping data/attributes and methods together within a class.
Through encapsulation, data is not accessible to the outside. It means that the internal details
of a class can be hidden from the outside. It can be accessible by it functions which are
wrapped in that class.

Example:

public class Student


{
private String name;
private int icNumber;
private String course;
private String address;

public String Display()


{
return name + " " + icNumber+ " "+course +
" "+address;
}
}

In a class Student above, attributes name, ic number, course and address only
can be accessed by the methods declared in the same class which is method Display().

13
iii. Inheritance
Inheritance is a mechanism in which one object acquires all the attributes and behaviours of
parent object. The class with the common features is called superclass. The class that inherit
common features from the superclass is called subclass.

superclass/parent
B
subclass/child

Figure 2.1:Single Inheritance

B C
Figure 2.2 : Single Inheritance with more than one subclass

Figure 2.1 shows that Class B inherit the common features of superclass A. Figure 2.2 shows
that Class B and Class C inherit the common features of superclass A.

Example:

Student
Attributes : name, age, course, fee

Part time Full time


Attributes: additional fee Method:
Method : Display() Display()

Figure 2.3 : Superclass and Subclass

Part time and fulltime student have common attributes/features of name, age and course.
They can share those attributes. But the part time student also has their own features such as
additional fee. partTime and fullTime classes can access all attributes declared
in its parent class which is Student.

14
Example:

public class Student


{
protected String name;
protected int icNumber;
protected String course;
protected double fee;
}

public class partTime extends Student


{ private double additionalFee;

public String Display()


{
return name + " " + icNumber+ " "+course + " " +fee+ ” “ +
additionalFee;
}}

public class fullTime extends Student


{ public void Display()
{
System.out.println(name + " " + icNumber+ " "+course
+" "+fee;
}}

iv. Polymorphism
Polymorphism means one object to take on many forms. It occurs when there is a hierarchy
of classes (inheritance).

Example:

public class Student


{ private String name;
private int icNumber;
private String course;
private String address;

public String Display() {


return name + " " + icNumber+ " "+course + " "+address;
}

15
}

public class partTime extends Student


{ private double additionalFee;
private double fee;
public void Display()
{
System.out.println( “I’m part time student”);
System.out.println( “My fee:” +fee+additionalFee);
}
}

public class fullTime extends Student {


private double fee;
public void Display()
{
System.out.println( “I’m full time student”);
System.out.println( “My fee:” +fee);
}
}

From the above example, each of the child classes and parent class has a separate
implementation for the method Display(). This is how polymorphism is used. There are
different classes with a method of the same name and even the same parameters but with
different implementation. The parent class Student has a Display() method, the child
class partTime has its own Display() method and the another child class fullTime
has its own Display() method.

Message passing
Message Passing means sending and receiving the information by the object. In OOP, it
involves specifying the name of objects, the name of the function, and the information to be
sent.

Example 1 : Message Passing through Methods

public class Number {


public void calcAdd(int no1, int no2, int& total) {
total = no1 + no2;
}

public void Display(int no1, int no2, int total) {


System.out.println(“Number 1 :” + no1+ "\nNumber 2 :”
+no2+"\nTotal :”+total);
}
}

import javax.swing.*;
public class NumberApp {
public static void main() {
int num1 = Integer.parseInt(JOptionPane.showInputDialog

16
("Insert Number 1 :");
int num2 = Integer.parseInt(JOptionPane.showInputDialog
("Insert Number 2 :");

Number objNum = new Number();


objNum.calcAdd(num1,num2,total);
objNum.Display(num1,num2,total);
}
}

From the above example, in the main(), it shows that data for variable num1 and num2 are
inserted. Then using the object named objNum, both data are sent into method named
calcAdd(). In calcAdd(), the addition process is done and the result is assigned into
the variable named total. Then the total sent through reference parameter into the main().
Next, through objNum as well, the Display() method is called and again data for num1,
num2 and total are sent for printing.

Example 2 : Message Passing through Constructors

public class Number


{
public int number1;
public int number2;
public int total;

public Number(int no1, int no2)


{
number1 = no1;
number2 = no2;
}

public void Calc_Display()


{
total = number1 + number2;
System.out.println(“Number 1 :” + number1+ "\nNumber 2:”
+number2+"\nTotal :”+total);
}
}
import javax.swing.*;
public class NumberApp
{

public static void main(String[] args)


{
int num1 = Integer.parseInt(JOptionPane.showInputDialog
("Insert Number 1 :");
int num2 = Integer.parseInt(JOptionPane.showInputDialog
("Insert Number 2 :");

17
Number objNum = new Number(num1,num2);
objNum.Calc_Display();
}
}

From the above example, it shows that data for variable num1 and num2 are inserted in the
main application and both are sent to the method named Number() that is known as
constructor.
In fact, there are many ways to send and to process data in a method. We can send data either
using a method or using a constructor. To process data, it can be processed in different
methods or in the same method which data are transmitted.

Exercise
1. List and explain the characteristics of OOP.
2. How many objects can be created from one class?
3. Describe about inheritance and give the example of super class related to sub class.
4. Describe about polymorphism and give the example in how situation polymorphism
involved.

18

You might also like