You are on page 1of 38

Computing II

Tutorial 2

Prepared by: Ng Mee Mee


Outlines

 Key Concepts of Unit 2


 Introduction
 Marking Scheme and TMA2 support
Key Concepts of Unit 2

 Describe and apply information hiding and


encapsulation.
 Develop class constructors
 Describe and apply inheritance
 Describe and apply method overloading and
polymorphism.
 Describe and apply abstract classes and
methods.
Introduction
 Class is a template or blueprint of a group of objects
for modeling real-world objects of the same type.
 For example, bus and car are types of vehicle. Vehicle is a
general class; bus and car are specific class.
 Classes encapsulate data and function into a single
entity.
 Classes are like cookie cutters, used to create
instances, or objects
 Objects communicate by sending each other
messages.
 when an object receives a message it executes a
corresponding method.
A rectangle class’s attributes
and method correspond to the
object properties and behaviours
Question
 A company needs an application that calculates
the gross pay per week for each of its employees.
Each employee’s weekly salary is based on the
employee’s number of hours worked and hourly
rate. A standard work week is 40 hours. Any time
worked over 40 hours in a week is considered
“overtime” and employees earn 1.5 times hourly
rate.
a) Design classes that can model the above scenario.
b) Define the attributes and methods of each class that you
defined in question a).
Information Hiding (or data
hiding)
 The idea of information hiding suggest that
object attributes should be kept out of reach
from the users of the object, so that it is not
possible to assign invalid values to the
attributes
How to apply information hiding
in java program?
 Declare all the class’s attributes as private to
prevent other classes to access them
 Provide an accessor method to allow other
classes to access its attributes
 Provide a mutator method to allow other
classes to modify or validate its attributes
Sample
Code Person.java
public class Person{
private String name;
private int age;

public String getName(){ //accessor method


Return name;
}
public int getAge(){ //accessor method
return age;
}
public void setName(){ //mutator method
this.name = name;
}
public void setAge(){ //mutator method
this.age = age;
}
}
Encapsulation

 The concept of encapsulation recommends


that internal operations are transparent to the
users of the class, so that it is not necessary
for the users of the class to know its internal
operations.
 If its internal operations need modifications,
the changes are localised, and no other
classes need modifications.
How to apply encapsulation in
java program?
 Declare all methods in class as public, so that
other classes can access them without
knowing the implementation details of the
methods.
 For example,
 Person p1 = new Person();
 p1.getName();
 p1.getAge();
Sample
Code Person.java
public class Person{
private String name;
private int age;

public String getName(){ TestPerson.java


return name;
}
public int getAge(){
return age;
}
public class TestPerson{
public void setName(){
this.name = name; Person p1 = new Person();
} p1.getName();
public void setAge(){ p1.getAge():
this.age = age;
} }
}
Constructors
 A special method that is executed during the
process of creating an object.
 For example, when java system executed this statement,
Person p1 = new Person();
 It is used to initialize the data members of an object
 For example,
public Person(){
name =“Susan”;
age=20;
}
Constructors

 Constructors must have the same name as


the class itself.
 Constructors do not have a return type—not
even void.
 Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing
objects.
Types of Constructors
1. Constructors without parameters (Default
constructor)
 Example:
public Person(){
}

2. Constructors with parameters


 Example:
public Person( String name, int age){
this.name = name;
this.age = age;
}
Note: if you do not define a constructor in a java program, the java
system will automatically provide you a default constructor.
Sample Person.java
Code
public class Person { public int getAge(){
private String name; return age;
private int age; }
public void setName(){
this.name=name;
public Person() {
}
name="unknown"; public void setName(){
age=0; this.name=name;
} }
public Person(String name, int public void setAge(){
age){ this.age= age;
this.name = name; }
this.age=age; public String toString(){
} String output;
public String getName(){ output="Name:" + name +
"\nAge:" + age;
return name; return output;
} }
Sample
Code TestPerson.j
ava Calling default
constructor
public class TestPerson{
 public static void main(String[] args) {
 Person p1 = new Person();
 Person p2 = new Person("susan",20);
 System.out.println(p1.toString());
 System.out.println(p2.toString());
 }
} Calling constructor which receive two
parameters
Question

 Declare a default constructor and a


constructor with parameters for
FullTimeEmployee class
inheritance
 “is-a” relationship
 Single inheritance:
 Subclass is derived from one existing class
(superclass).
 Multiple inheritance:
 Subclass is derived from more than one
superclass.
 Not supported by Java.
 In Java, a class can only extend the definition of
one class.
Inheritance
 Classes can inherit methods and data from
other classes. This makes it easy to extend
the capabilities of a class without changing
the original.

 For example,
 Full-time employee class and part-time employee
class not only inherit all the methods and data
which defined in Person class, but also can define
its own method and data. Every employee is a
person.
Inheritance Hierarchy
Person

FullTimeEmployee PartTimeEmployee

modifier(s) class ClassName extends ExistingClassName


modifier(s)
{
memberList
}
Public class FullTimeEmployee extends Person {
}
Superclasses and
Subclasses
 You can derive a new class from an
existing class. This is known as class
inheritance.
 The new class is called a subclass, child
class or derived class
 The existing class is called a superclass,
parent class or base class.
Person
-name: String
-age: int Superclass
+Person() or
+Person(name: String, age: int) Baseclass
+getName(): String
+getAge(): int Or
+setName(name: String): void parent class
+setAge(age: int): void
+toString(): String

FullTimeEmployee
-payRate: double
subclass
-hoursWorked: double or
+PartTimeEmployee()
derivedclass
+PartTimeEmployee(name:String, rate:double, hours:double) or
+getPayRate(): double
+getHoursWorked(): double
child class
+setNameRateHours(name:String, rate:double, hours:double):void
+calculatePay(): double
+toString(): String
Overloading methods
 If a class definition has two different methods
with same name but different parameter lists,
it is considered to be overloading
 For example,
 The println() method defined in the class
java.io.PrintStream.
 There are 10 println() methods with different
parameter lists can be used to print primitive type
value(int, long, double) and non-primitive type
value( String, Object)
Sample
Code
Overloading methods in
constructors
public Person() {
name="unknown";
age=0;
}
public Person(String name, int age){
this.name = name;
this.age=age;
}
Overriding methods in the
Superclass
 If a subclass defines a method with the same
name and parameter list as a method in
superclass, it is considered to be overriding,
and the method defined in the subclass
overrides the one defined in the superclass.
Sample
Code
override toString( ) method
toString()
method in
public class Person {
superclass
public String toString(){
return name;
}
}

public class PartTimeEmployee extends Person{


public String toString(){
return (super.toString() + "'s wages are: RM" + String.format("%.2f",
calculatePay()));
} toString() method in
subclass
Overloading vs. overriding

 Pls refer course material Unit2 on page 66.


Polymorphism
 Polymorphism is the ability to send the same
message to several different types of object and
each behaves in its own particular way in
response.
 Java allows us to treat an object of a subclass
as an object of its superclass. In other words, a
reference variable of a superclass type can point
to an object of its subclass.
 As a method to be executed is determined while
the software is executing, it is known as the late
binding or dynamic binding or rum-time binding
or virtual method invocation.
Polymorphism
 The term polymorphism means to assign
multiple meanings to the same method name.
 In Java, polymorphism is implemented using late
binding.
 The reference variable name or nameRef can
point to any object of the class Person or the
class PartTimeEmployee.
 These reference variables have many forms,
that is, they are polymorphic reference variables.
They can refer to objects of their own class or to
objects of the classes inherited from their class.
Sample
Code TestEmployee.j
ava{
public class TestEmployee nameRef point to the object
PartTimeEmployee
public static void main(String[] args) {
nameRef point to the object
Person name,nameRef; FullTimeEmployee
PartTimeEmployee partEmp;
FullTimeEmployee fullEmp;

name = new Person("John");


partEmp = new PartTimeEmployee("Susan",4,30);
fullEmp = new FullTimeEmployee("Shelly",4,42);
nameRef = partEmp; The method toString of
PartTimeEmployee
System.out.println(nameRef.toString());
executes, not the
nameRef = fullEmp; method toString of the
System.out.println(nameRef.toString()); class Person
}
}
Abstract class and method
 An abstract method is a method that has only the
heading with no body.
 For example:
 public abstract void print();
 public abstract double calculatePay();
 An abstract class is a superclass which contain
abstract methods. It defines a general type and what
behaviours such a general type can perform and
some of the behavours can be undefined and leave
it for subclass to define those behaviors.
 For example:
 public abstract class Shape{
Abstract Class
 Can contain instance variables, constructors, the
finalizer, nonabstract methods and abstract
methods.
 If the class contain abstract method, then the class
must be declared abstract.
 You cannot instance an object of an abstract class.
 You can only declare a reference variable of an
abstract class type
 You can instantiate an object of a subclass of an
abstract class, but only if the subclass gives the
definitions of all the abstract methods of the
superclass.
Abstract Class Example
public abstract class
AbstractClassExample {
protected int x;
public void abstract print();

public void setX(int a) {


x = a;
}

public AbstractClassExample() {
x = 0;
}
}
Abstract Class Example

 Pls refer course material Unit2 on page 71 –


Modelling a pet shop using abstract classes
Three key features of an Object-
oriented programming
1. Encapsulation
2. Inheritance
3. Polymorphism
 Promoting software writing and improving
software productivity and maintainability
TMA 2 (15%)
 Individual Assignment
 Your are required to answer ONLY ONE question.
 Submit soft copy (virus free) and hard copy of the TMA2 in word
processed (1.5 spacing).
 You may send your soft copy to me at meemeng@yahoo.com
 Submission date 23/09/07
 Late submission
 Over 7 days

 Contact tutor before or on the due date


 Over 8 – 14 days
 Course Coordinator
 Up to 21 days
 Dean
TMA2 – Question 1

 Pls refer Malik textbook on page 683

You might also like