Classes
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
• A class is a template that contains
§ the data variables
§ the methods that operate on those data variables
(following some logic)
§ The class is the foundation on which the entire Java
language is built.
§ All the programming activity happens inside classes.
§ Next we explore:
§ writing classes
§ creating objects from classes (Inheritance)
Unit
of
Code
in
Java
• Class
is
the
minimalist
possible
program
you
can
write
in
java,
below
is
your
first
program
class HelloWorld {
public static void main(String[] args){
System.out.println(”HelloWorld!");
}
}
• class keyword and class name
• main method – entry point to program
• argument list passed into program
• command to print out a message to the screen
Class Syntax
§ A class is declared by using the keyword class. The
general syntax for a class declaration is
<modifier> class <className> { }
§ <className> specifies the name of the class,
§ class is the keyword
§ <modifier> specifies some characteristics of the class.
§ The <modifier> specification is optional
§ The class keyword and <className> are
mandatory.
Access Modifers
• Modifiers can be broadly grouped into the following two categories:
• Access modifiers determine from where the class can be
accessed:
• e.g. private, protected, and public
• If you do not specify an access modifier, the default access
is assumed.
• Other modifiers specify how the class can be used:
• e.g. abstract, final, and strictfp
Some Examples:
class MyClass { }
abstract class MyClass { }
final public class MyClass{}
An Encapsulated Example
The class code that contains the class members is written inside two curly braces
You will see slides on why we call it encapsulation
Example: ClassRoom.java
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:
<className> <variableName> = new <classConstructor>;
§ <variableName> is the name of the object reference: it will refer to the object (on
Heap) that you want to create
§ <className> is the name of an existing class
§ <classConstructor> is a constructor of the class.
§ The right side of the statement creates the object of the class specified by
<className> with the new operator
§ The object is assigns it to <variableName> (i.e. <variableName> points to it)
§ 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);
System.out.println("Room number:”+ room1.getRoomNumber());
System.out.println("Total seats:”+ room1.getTotalSeats());
// calling getter methods
}
}
Output:
Room number: MH227
Total seats: 30
The use of new Keyword
§ The object is created in the following line of code:
ClassRoom roomOne = new ClassRoom();
§ What happens:
1. The left side declares a reference variable roomOne of class
ClassRoom
2. The right side creates an object of class ClassRoom with the
operator new
3. The assignment operator = assigns the newly created object
to the reference variable roomOne
Reference Variable
• Note that the variable roomOne does not hold the object
§ It is a reference to the object (living on the heap)
§ It is called a reference variable, or object reference.
§ However, for brevity, the object references sometimes are also called
objects
Summary Classes and Objects
To summarize :
§ We instantiated the class ClassRoom inside another class called
ClassRoomManager
§ 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
§ It is possible to create more than one instance of a class.
§ 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
§ Changing the value of an instance variable in one object of a
class does not change the value of the same variable in another
object of the same class.
§ 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
Public class Car{
public String carName= “figo”;
public String color=“red”;
public void testEngineEfficiency(){
}
public void automaticBreakSystem(){
}
} taken from http://learn-java-with-comics.blogspot.com
Solution: Encapsulation
Public class Car{
public String carName= “figo”;
private String color=“red”;
public void testEngineEfficiency(){
}
public void automaticBreakSystem(){
}
} taken from http://learn-java-with-comics.blogspot.com
Data Hiding
Public class Car{
public String carName= “figo”;
private String color=“red”;
public void testEngineEfficiency(){
}
public void automaticBreakSystem(){
}
} taken from http://learn-java-with-comics.blogspot.com
Inside and Outside
Public class Person
{
// you are inside the person class
private int age;// always make fields private
public int getAge(){ // and methods public so thatthey can be called
return this.age;
}
public void setAge(int age){
this.age = age;
}
}
Public class Main{
// you are outside of the Person class
public static void main(String args[]){
Person me = new Person();
me.setAge(35);//since setAge is public we can call it from outside
}
}