0% found this document useful (0 votes)
41 views35 pages

4 Chapter 3 - Basic Concept of Classes & Encapsulation

Uploaded by

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

4 Chapter 3 - Basic Concept of Classes & Encapsulation

Uploaded by

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

Chapter 3:

Basic
Concept of
Classes ‫ﻣﺤﻤﺪ ﺻﻮﻓﯿﺎن ﺳﻠﯿﻤﺎن‬
Dr. Mohd Suffian Sulaiman
College of Computing, Informatics & Mathematics
Universiti Teknologi MARA
Learning Outcome

 Class and object concept


 Constructing a class (programmer defined class)
 Modifiers
 Dot notation
 Object creation from a class
 Basic types of methods
 Encapsulation
Class and object concept

 An object is an instance of a class. An object can be assigned to be a variable


to the class.
 A class can be used as a data type. When you create a class in Java, you are
defining a new type that can be used to create objects.
 The class is a blueprint or template for creating objects, and it defines the
attributes and methods that objects of that class can have.
 An object combines attribute(s) and the method(s) in a single unit.
Constructing a class (programmer
defined class)
 When a Java application is run, object(s) can be created and their method(s)
can be invoked (called) to perform specific tasks.
 A class is a description of a kind of object in Java. A programmer can define
their own classes or use predefined classes from the Java Class Library.
 A class is simply a plan for a possible object. It does not by itself create any
object.
 When a programmer wants to create an object the keyword new operator is
used with the name of the class. Creating an object is called instantiation.
Constructing a class (programmer
defined class)
Template for Class Definition

Import Statements

Class Comment

class {
class {
Class Name

Data Members

Methods
(incl. Constructor)

}
}
Modifiers
 Modifiers in Java are keywords that are used to define the access and scope of
classes, variables, methods, and other program elements in Java. They are used to
control the visibility and accessibility of the program elements.
 Java provides four access modifiers: public, protected, private, and the default (no
keyword).
 private - restricts access to only the class in which the program element is
declared, for example:
private int num1, num2;
 public - allows other classes and objects to access a program element from
anywhere in the program, for example:
public int area(){
return width*length;}
 protected - allows a class member to be accessed by any subclass of the class in
which it is declared, as well as any other class in the same package, for example:
protected String name;
Example : class, attribute and method
 Create a class called “Myclass” with two attributes, x and y with private
modifiers. Initialize x as 3 and y as 5 :

public class MyClass{ class


private int x;
attribute
private int y;

public MyClass(){ method


x = 3;
y = 5;
}
}
Dot notation

 In Java, dot notation refers to the use of the dot (.) operator to access
members of an object or class.
 When you create an object from a class, you can use the dot notation to
access the members (variables and methods) of that object.

 E.g., An object myObj used dot notation to access the next() method in
Scanner class.
Object creation from a class (1st approach)
‘new’ constructor
class object
keyword method

MyClass myObj = new MyClass( );

object creation
Invoking data member

Output:
5
Object creation from a class (2nd approach)
class object

MyClass myObj;
myObj = new MyClass( );
‘new’ constructor
keyword method

object creation
Invoking data
member Output:
5
Basic types of methods

 Constructor
 Default
 Normal / Parameterized
 Copy
 Setter / Mutator
 Getter/ Accessor / Retriever
 Processor
 Printer
 toString() method (also type of printing method)
Constructor

 A special method that is called when an object is created from a class.


 It is used to initialize the object's state and perform any necessary setup tasks
before the object can be used.
 A constructor has the same name as the class it belongs to and does not have
a return type (not even void)
 Always define a constructor and initialize data members fully in the
constructor so an object will be created in a valid state.
 All classes have constructors by default: if you do not create a class
constructor yourself, Java creates one for you. However, then you are not
able to set initial values for object attributes.
 Three types of constructor: (1) Default, (2) Normal/parameterized and (3)
Copy
Default constructor

 A constructor that is automatically provided by the compiler if no other


constructors are explicitly defined in a class.
 An object is still guaranteed to be initialized to a constant state due to
default argument.
 For example:
//default constructor
public Rectangle(){
//width will be 0.0 (default for double)
//name will be null (default for String)
}

Output:
0.0
null
Normal/parameterized constructor

 Used to override default arguments set in default constructor.


 Data members in the created object will set by the value sent through its
parameters.
 For example:

//normal constructor
public Rectangle (double w, double l){
width = w;
length = l;
}

Output:
0.0
0.0
Example: normal/parameterized constructor

Which one is constructor?


Which one is an object?
Copy constructor

 Allow one object to copy the value of another object’s


data members.
 For example:

//copy constructor
public Rectangle (Rectangle rect) {
width = rect.width;
length = rect.length;
}

Output:
10.0 and 15.0
10.0 and 15.0

Object myRec2 copy the value of object myRec


Example: copy constructor

Which one is constructor?


Which one is an object?

Output:
Setter / Mutator

 Sets a property (data / attribute) of an object.


Usually, the word set is being used.
 Example:
a) void
void setRectangle
setRectangle (double
(double w,
w, double
double l){
l){
width = w;
width = w;= l;
length
} length = l;}
b) void setLength(int l ){
length = l;}
c) void setWidth(int w) {
width = w; }

Output:
10.0 and 15.0
Getter / Accessor / Retriever

 Return information about an object


 Example:
//returns the length of a rectangle
public double getLength(){
return length;
public double getLength(){
}
return length;}
 getLength()– return information about
the length of a rectangle

Output:
10.0
15.0
Processor

 A function used to perform calculation / operation to


update specific data members or might return a specific
value.
 For example to calculate the area of a rectangle:
public
public double
double calculateArea(){
calculateArea(){
return (width
return * length);
(width * length);}
}

Output:
150.0
Printer
 A function used to display information of a class. Usually
the word display or print had being used.
 For example to display all information about the
object of a rectangle:

publicvoid
public voiddisplayArea(){
displayArea(){
System.out.println(“width:“+getWidth());
System.out.println(“Width“+getWidth());
System.out.println(“length:“+getLength());
System.out.println(“Length“+getLength());
System.out.println(“the area is:“+calculateArea();
} System.out.println(“The area is“+calculateArea();}

Output:
width: 10.0
length: 15.0
the area is: 150.0
toString()
 Method that returns a string representation of an object.
 For example:

public String toString(){


return
public “Width
String “+ getWidth() +”\n”
toString(){
return “Width “+ getWidth() +”\n”
++“Length
“Length“+ “+ getLength()
getLength() + “\n”
+ “\n”
++“The
“Thearea is is
area “ +“ calculateArea();
+ calculateArea();}
}

Output:
Width 10.0
Length 15.0
The area is 150.0
Basic types of methods application:
Example 1
• Create two classes, Bicycle (class that has all the attributes and methods)
and BicycleAPP (class that contain the main() method (code to be executed))
• The relationship of BicycleApp class to Bicycle class is dependency.

Relationships:

BicycleApp class is a ‘main class’ or ‘entry point class’ that contain


the main() method, to start the execution of the program
Example 1

Which one is constructor? Which one is class?

Which one is an object?


Which one is getter?
How many object is created?
Which one is setter?
Example 2

Create two classes, Students and StudentsAPP


Example 2
Encapsulation

 The meaning of encapsulation, is to make sure that "sensitive" data is hidden


from users. To achieve this, you must:
 Declare class variables/attributes as private (only accessible within the same
class)
 Provide public setter and getter methods to access and update the value of a
private variable
Encapsulation

As the name variable is declared as private, we


cannot access it from outside class

Instead, we use the getName() and setName()


methods to access and update the variable name.
Why Encapsulation?

 Better control of class attributes and methods


 Class variables can be made
 read-only (if you omit the set method), or
 write-only (if you omit the get method)
 Flexible - the programmer can change one part of the code without affecting
other parts
 Increased security of data
Exercise 1
Exercise 2
Exercise 3
Answer Exercise 1

 1(a)(i) Star starObj = new Star();


 1(a)(ii) starObj.starNum = 1;
starObj.starName = “Corvus”;
 1(a)(iii) System.out.println(starObj.starNum);
System.out.println(starObj.starName);
Answer Exercise 2

 1(a) class : Product


attribute : productNumber
productName
 1(b) public class Product{
int prodNumber;
String prodName;
public Product(int pNum, String pName){
prodNumber = pNum;
prodName = pName;
}
}
 1(c) public class TestP{
public static void main (String[] args) {
Product prod = new Product(3001, “computer”);
System.out.println(prod.prodNumber + “ “ +prod.prodName);
}
}
Answer Exercise 3
 (i) public SalesPerson(String n, int i, double bS, double mS){
name = n;
id = I;
basicSalary = bS;
monthlySalary = mS;
}
 (ii) public double calcCommission(){
double comRate;
if(monthlySale<500)
ComRate = 0.05;
else if (monthlySale>=500 && monthlySale <1000)
ComRate = 0.10;
else if (monthlySale>=1000 && monthlySale <2000)
ComRate = 0.15;
else
ComRate = 0.20;
return comRate;
}

You might also like