J.E.D.I
9.3.2 Encapsulation
Encapsulation is the method of hiding certain elements of the implementation of a certain class. By placing a boundary around the properties and methods of our objects,
we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways.
We can prevent access to our objects data by declaring them declaring them in a certain way such that we can control access to them. We will learn more about how Java
implements encapsulation as we discuss more about classes.
9.3.3 Class Variables and Methods
In addition to the instance variables, it is also possible to define class variables, which are variables that belong to the whole class. This means that it has the same value for
all the objects in the same class. They are also called static member variables.
To clearly describe class variables, lets go back to our Car class example. Suppose that our Car class has one class variable called Count. If we change the value of Count to 2,
all of the objects of the Car class will have the value 2 for their Count variable.
Car Class Object Car A
Object Car B
In s
ta n
c e
V a
ri a
bl e
s Plate Number
ABC 111 XYZ 123
Color Blue
Red Manufacturer
Mitsubishi Toyota
Current Speed 50 kmh
100 kmh
C la
s s
V a
ri a
bl e
Count = 2
In s
ta n
c e
M e
th o
ds Accelerate Method
Turn Method Brake Method
Table 19: Car class methods and variables
Introduction to Programming I 130
J.E.D.I
9.3.4 Class Instantiation
To create an object or an instance of a class, we use the new operator. For example, if you want to create an instance of the class String, we write the following code,
String str2 = new String“Hello world”; or also equivalent to,
String str2 = Hello;
The new operator allocates a memory for that object and returns a reference of that memory location to you. When you create an object, you actually invoke the class
constructor. The constructor is a method where you place all the initializations, it has the same name as the class.
Introduction to Programming I 131
Figure 9.1: Classs Instantiation
J.E.D.I
9.4 Methods