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

6 Encapsulation

Encapsulation involves grouping data and behaviors into classes. The document discusses class design principles like identifying main nouns as classes and descriptive nouns as fields. It explains how to declare classes with fields, constructors, getters, setters, and other methods. Constructors initialize new objects, and objects are instantiated using the new operator followed by a constructor call. Fields and methods are then accessed using dot notation on the object reference.

Uploaded by

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

6 Encapsulation

Encapsulation involves grouping data and behaviors into classes. The document discusses class design principles like identifying main nouns as classes and descriptive nouns as fields. It explains how to declare classes with fields, constructors, getters, setters, and other methods. Constructors initialize new objects, and objects are instantiated using the new operator followed by a constructor call. Fields and methods are then accessed using dot notation on the object reference.

Uploaded by

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

Encapsulation

Objectives
• Class and Object
• How to identify classes
• Hints for class design
• How to declare/use a class
• Member functions
• Common modifiers (a way to hide some members in a
class)
• Case study
Encapsulation

Aggregation of data and behavior.


• Class = Data (fields/properties) + Methods
• Data of a class should be hidden from the outside.
• All behaviors should be accessed only via methods.
• A method should have a boundary condition: Parameters
must be checked (use if statement) in order to assure that
data of an object are always valid.
• Constructor: A special method it’s code will execute when
an object of this class is initialized.
• Getters/Setters: implementing getter and setter is one of
the ways to enforce encapsulation in the program’s code.
How to Identity a Class
• Main noun: Class
• Nouns as modifiers of main noun: Fields
• Verbs related to main noun: Methods
For example, details of a Main noun: Student
Auxiliary nouns:code , name,
student include code, name, bYear, address;
year of birth, address. verbs: input() , output()
Write a Java program that will
allow input a student, output
his/her.
Hints for class design

A UML class diagram is used to represent


the Student class
Student class

Code: String
name: String fields
bYear: int
address: String

Input(): void methods


output():void
Declaring/Using a Java Class

[public] class ClassName [extends FatherClass] {


[modifier] Type field1 [= value];
[modifier] Type field2 [= value]; Modifiers will be
// constructor introduced later.
[modifier] ClassName (Type var1,…) {
<code>
How many
}
constructors should
[modifier] Type methodName (Type var1,…) { be implemented? ➔
<code> Number of needed
} ways to initialize an
……. object.
}
What should we will write in constructor’s body? ➔ They usually
are codes for initializing values to descriptive variables
Member functions: Constructors

• Constructors that are invoked to create


objects from the class blueprint.
• Constructor declarations look like method
declarations—except that they use the
name of the class and have no return type.
• The compiler automatically provides a no-
argument, default constructor for any class
without constructors.
Member functions: Constructors

//default constructor
public Student(){
code=“SE123”;
name=“Hieu”;
bYear= 2000;
address=“1 Ba Trieu , HN”.
}
//constructor with parameters
public Student(String code, String name, int bYear, String address){
this.code=code;
this.name=name;
this.bYear= year;
this.address=address.
}
The current object: this

• The keyword this returns the address of the current


object.
• This holds the address of the region of memory that
contains all of the data stored in the instance variables of
current object.
• Scope of this: this is created and used just when the
member method is called. After the member method
terminates this will be discarded
Member functions: Getter/Setter

• A getter is a method that gets the value of


a property.
• A setter is a method that sets the value of
a property.
• Uses:
➢for completeness of encapsulation
➢to maintain a consistent interface in case
internal details change
Member functions: Getter/Setter

• For example:
public String getName(){
return name;
}
public void setName(String name){
if(! name.isEmpty())
this.name=name;
}
Member functions:
other methods
• Typical method declaration:
[modifier] ReturnType methodName (params) {
<code>
}

• Signature: data help identifying something


• Method Signature:
name + order of parameter types
Member functions:
other Methods
• For example:
public void input(){
//code here
}
public void output(){
//code here
}
Passing Arguments a Constructor/Method

• Java uses the mechanism passing by


value. Arguments can be:
• Primitive Data Type Arguments
• Reference Data Type Arguments (objects)
Creating Objects

• Class provides the blueprint for objects; you create an


object from a class.
Student stu = new
Student(“SE123”,”Minh”,2000,”1 Ba Trieu”);
• Statement has three parts:
• Declaration: are all variable declarations that associate a
variable name with an object type.
• Instantiation: The new keyword is a Java operator that
creates the object (memory is allocated).
• Initialization: The new operator is followed by a call to a
constructor, which initializes the new object (values are
assigned to fields).
Type of Constructors
Create/Use an object of a class
• Default constructor: Constructor with no parameter.
• Parametric constructor: Constructor with at least one
parameter.

• Create an object
ClassName obj1=new ClassName();
ClassName obj2=new ClassName(params);
• Accessing a field of the object
object.field
• Calling a method of an object
object.method(params)
Demo: If we do not implement any
constructor, compiler will insert to the class a
system default constructor

In this demonstration (package


point1):
- The class IntPoint1 represents a
point in an integral two
dimensional coordinate.
- The class IntPoint1_Use having
the main method in which the
class IntPoint1 is used.
Demo: If we do not implement any
constructor, compiler will insert to the class a
default constructor
System constructor will clear all
bits in allocated memory Order for
initializing an
object

(2) Setup
values

y 0
100 x 0

(1) Memory
allocation

p 100
An object variable is a reference
Demo: If we implement a constructor,
compiler does not insert default constructor

This demonstration will depict:


- The way to insert some
methods automatically in
NetBeans
- If user-defined constructors
are implemented, compiler
does not insert the system
default constructor
Demo: If we implement a constructor,
compiler does not insert default constructor
Insert constructor

Parameter names are the same as those


in declared data filed. So, the keyword
this will help distinguish field name and
parameter name.
this.x means that x of this object
Demo: If we implement a constructor,
compiler does not insert default constructor
Accessing each data field is usually supported by :
A getter for reading value of this field
Insert getter/setter A setter for modifying this field
Demo: If we implement a constructor,
compiler does not insert system constructor
Explain the result of the following program
Demo: Methods with
Arbitrary Number of Arguments
A group is treated as an array
group.length →number of elements
group[i]: The element at the position i
Case study
• Problem:
A sports car can be one of a variety of colours,
with an engine power between 100 HP and 200
HP. It can be a convertible or a regular model.
The car has a button that starts the engine and a
parking brake. When the parking brake is
released and you press the accelerator, it drives
in the direction determined by the transmission
setting.
Report…
Class Design
From the problem description, concepts in the problem domain
are expressed by following classes:
Report…

• A UML class diagram is used to represent


the Car class
Car

- Colour: String
- EnginePower: int
- Convertible: boolean
- parkingBrake: boolean

+Car()
+Car(String, int, boolean, boolean )
+pressStartButton():void
+pressAcceleratorButton(): void
+ getColour(): String
+ setColour(String): void

Implement
Implement
Implement
Summary
• The anatomy of a class, and how to declare
fields, methods, and constructors.
• Hints for class design:
• Main noun → Class
• Descriptive nouns → Fields
• Methods: Constructors, Getters, Setters, Normal methods
• Creating and using objects.
• To instantiate an object: Using appropiate
constructior
• Use the dot operator to access the object's
instance variables and methods.

You might also like