Classes Encapsulation
Classes Encapsulation
in Java
SZABIST
Islamabad
Agenda
• What
are
classes?
• Class
is
a
unit
of
code
in
java
• Class
Syntax
• Access
Modifiers
• An
Encapsulated
Example
• CreaEng
Objects
• The
use
of
new
keyword
• Reference
Variable
hold
address
of
the
created
object
• EncapsulaEon/Data
hiding
• Inside
and
outside
of
a
class
What are Classes
Some Examples:
class MyClass { }
1. class ClassRoom {
2. private String roomNumber;
3. private int totalSeats = 60;
4. private static int totalRooms = 0;
5. void setRoomNumber(String rn) {
6. roomNumber = rn;
7. }
8. String getRoomNumber() {
9. return roomNumber;
10.}
11.void setTotalSeats(int seats) {
12. totalSeats = seats;
13.}
14. int getTotalSeats() {
15. return totalSeats;
16. }
17. }
Creating Objects: Syntax
§ Classes can be considered as data types
§ e.g. You can declare a variable as a primitive data type and assign it a value, as
follows: int i=0;
§ Similarly, you can declare a variable (a reference variable) of a class and assign
it a value with the following syntax:
§ <variableName> is the name of the object reference: it will refer to the object (on
Heap) that you want to create
§ The right side of the statement creates the object of the class specified by
<className> with the new operator
§ Creating an object from a class this way is also called instantiating the class.
Creating Objects:Example
For example:
class ClassRoomManager {
public static void main(String[] args)
{
ClassRoom room1 = new ClassRoom();//create an object
room1.setRoomNumber("MH227");// call a setter
room2.setTotalSeats(30);
Output:
Room number: MH227
Total seats: 30
The use of new Keyword
2. The right side creates an object of class ClassRoom with the
operator new
§ However, for brevity, the object references sometimes are also called
objects
Summary Classes and Objects
To summarize :
§ We declared an object reference roomOne that points to the newly created object
§ We invoked methods on the object roomOne (the object reference), which is of type
ClassRoom
§ Instantiating a class and invoking its methods is called accessing a class (or object)
and its methods.
§ The new operator creates the object dynamically, which means that it creates it at
runtime, not at compile time.
§ When the Java runtime system executes the statement with the new operator, it :
§ allocates memory for the instance (object) of class ClassRoom
§ and calls the constructor ClassRoom() to initialize this memory
§ Note: The terms instance and object are often used interchangeably
Static and Instance Variables/Fields
§ Each instance has its own copy of the nonstatic variables of the
class (but all instances share the static variables of the class).
§ For this reason, the nonstatic data members of a class are also
called instance variables
§ But if you change the value of a static variable of the class in one
object, the change will be visible from all the objects.
The Problem