6 Encapsulation
6 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
Code: String
name: String fields
bYear: int
address: String
//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
• 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>
}
• 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
(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
- 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.