Chapter- 2 Introduction to Class and Object
Chapter- 2 Introduction to Class and Object
OOP - CoSc2051 1
Outlines
Defining a class
Creating an Object
Instantiating and using objects
Printing to the Console
Methods and Messages
Parameter Passing
Comparing and Identifying Objects
Destroying Objects
Enumerated Types
Instance fields
Constructors and Methods
Access Modifiers
Encapsulation
OOP - CoSc2051 2
Defining a class
A class defines the properties and behaviors for objects.
Class is a user-defined data type that contain its own data members
and member functions.
The data members and member functions are accessed with the help
of objects.
It is the primary concept of object-oriented programming.
A class is used to organize information or data so a programmer can
reuse the elements in multiple instances.
OOP - CoSc2051 3
Class in java
• A class
– Classes are like object constructors for creating objects.
– The collection of objects is said to be a class.
– Classes are said to be logical quantities.
– Classes don’t consume any space in the memory.
– Class is also called a template of an object.
– Classes have members which can be fields, methods and constructors.
– A class has both static and instance initializers.
OOP - CoSc2051 4
Class in java
• A class definitions consists of:
1. Modifiers: Can be public or default access.
2. Class name: Initial letter.
3. Superclass: A class can only extend (subclass) one parent.
4. Interfaces: A class can implement more than one interface.
5. Body: Body surrounded by braces, { }.
AccessModifier class ClassName { //defines class
AccessModifier Type variableName; //declares class variables
…….
AccessModifier retrunType methodName(arguments){
//defines class methods
return values;
} //end of method
} //end of class
OOP - CoSc2051 5
Class in java
A class keyword is used to create a class.
Example: Student class:
package Oject_and_Class;
The variables or data defined within a class are called as instance variables.
OOP - CoSc2051 6
Object
Object-oriented programming (OOP) involves programming using
objects.
An object represents an entity in the real world that can be distinctly
identified.
For example, a student, a desk, a circle, a button, and even a loan
can all be viewed as objects.
An object has a three key characteristics a unique identity,
state, and behavior.
OOP - CoSc2051 7
Object
In OOP, the three key characteristics of objects:
• The object’s state
– also known as its properties or attributes
– is represented by data fields with their current values.
– An object’s state may change over time, but not spontaneously.
– A change in the state of an object must be a consequence of method
calls.
Object State Behavior
dog breed, isHungry eat, bark
grade book grades mean, median
light on/off switch
circle radius getArea()
OOP - CoSc2051 8
Object
In OOP, the three key characteristics of objects:
• The object’s behavior
– also known as its actions.
– is defined by methods.
– To invoke a method on an object is to ask the object to perform an
action.
Object State Behavior
dog breed, isHungry eat, bark
grade book grades mean, median
light on/off switch
circle radius getArea()
OOP - CoSc2051 9
Creating an Object
Objects are abstract data types (i.e.,
objects’ behavior is defined by a set of values and operations).
Classes are definitions for objects and objects are created from
classes.
Objects of the same type are defined using a common class.
An object is an instance of a class.
You can create many instances of a class.
Creating an instance is referred to as instantiation.
The terms object and instance are often interchangeable.
Objects are used to access the data members and functions of the class.
In Java, the new keyword is used to create new objects.
OOP - CoSc2051 10
Creating an Object
There are three steps when creating an object from a class
– Declaration
• A variable declaration with a variable name with an object type.
– Instantiation
• The 'new' keyword is used to create the object.
• "instantiating a class" same as "creating an object."
– Initialization
• The 'new' keyword is followed by a call to a constructor.
• This call initializes the new object.
OOP - CoSc2051 11
Creating an Object
Example from previous student class program
package Oject_and_Class;
public class Student {
String name = “Wakjira”;
public static void main(String[] args) {
//Creaing an object of student class
Student s = new Student(); // obj is an object
System.out.println(s.name);
}
}
OOP - CoSc2051 13
Initializing an Object – by Constructor
A constructor in Java is a block of code within a class that is used to
initialize objects of class.
In other words, a constructor is used to initializing the value of
variables.
The constructor should not have any return type even void also
because if there is return type then JVM would consider
as a method, not a constructor.
Let’s create a program where we will store data into an object using
constructor.
OOP - CoSc2051 14
Initializing an Object – by Constructor
package Oject_and_Class;
public class Student {
Initialization by
The process of assigning value of the variableconstructor
// Step 1: Declaration of instance variables.
is called
public String name;
initialization of state of an object.
public double test1 ,test2;
OOP - CoSc2051 15
Initializing an Object – Reference variable
Also initialize the value of objects through the reference variable.
E.g.:. we will initialize value of variables using object reference variable.
There are three steps to initializing a reference variable from scratch:
1. Declaring the reference variable;
2. Using the new operator to build an object and create a reference
to the object; and
3. Storing the reference in the variable.
Here's an example.
Counter c1 = new Counter ( );
first declares the variable c1 as something that can contain a reference to
a Counter object.
OOP - CoSc2051 16
Initializing an Object – Reference variable
package Oject_and_Class;
Weclass
public can also
Maininitialize
{ the value of objects through the
reference
public variable.
static void main(String[] args) {
//dispaly avg
System.out.println(studentX.getAverage());
}
}
OOP - CoSc2051 17
Initializing an Object – Using Method
A method in java is a set of code used to write the logic of
application which perform some specific task or operation.
When a method is called, it returns value to the caller.
It can also perform a task without returning any value.
It can be called from anywhere.
Therefore, we can initialize value of an object by using method.
Besides it, we will display state (data/value) of the objects by calling
calculate() method using object reference variable because we cannot
call directly non-static member into the static region.
OOP - CoSc2051 18
Initializing an Object – Using Method
package Oject_and_Class;
reference variable.
// Step 1: Declaration of instance variables.
public String name; Initialization
public double test1 ,test2; by reference
So, let’s make a program where we will initializeviarable
value of
// Step 2: Declare an instance method and print values.
variables using object reference variable.
public double getAverage(double test1, double test2){
//compute average test grade
double AvgGrade = (test1 + test2 ) / 2;
return AvgGrade;
}//end of getAverage method
}
OOP - CoSc2051 20
Reading Input from the Console
Reading input from the console enables the program to accept input
from the user.
Java uses System.out to refer to the standard output device and
System.in to the standard input device.
By default, the output device is monitor and the input device is keyboard.
To perform console output, you simply use the println() method to
display a primitive value or a string to the console.
Console input is not directly supported in Java, but you can use the
Scanner class to create an object to read input from System.in
E.g:
Scanner input = new Scanner(System.in);
OOP - CoSc2051 21
Reading Input from the Console
Scanner input = new Scanner(System.in);
The syntax new Scanner(System.in) creates an object of the
Scanner type.
The syntax Scanner input declares that input is a variable whose
type is Scanner.
The whole line Scanner input = new Scanner(System.in)
creates a Scanner object and assigns its reference to the variable
input.
To read a double value as follows:
double radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the
number to radius.
OOP - CoSc2051 22
Printing to the Console
print():
print() method in Java is used to display a text on the console.
This text is passed as the parameter to this method in the form of String.
This method prints the text on the console and the cursor remains at
the end of the text at the console.
println():
println() method in Java is also used to display a text on the console.
This text is passed as the parameter to this method in the form of String.
This method prints the text on the console and the cursor remains at
the start of the next line at the console.
The next printing takes place from next line.
OOP - CoSc2051 23
Methods
Methods can be used to define reusable code and organize and
simplify coding.
A method is a collection of statements grouped together to
perform an operation.
Methods define the behavior of a class.
Method is a member of the class which provides functionality for the
class.
A method can send, receive, and alter information to perform a task
in an application.
Java requires that every method be defined within a class or interface,
unlike C++ where methods (functions) can be implemented outside of
classes.
OOP - CoSc2051 24
Declaring Methods
A method declaration consists method name, parameters, return value
type, and body.
The syntax for defining a method is as follows:
modifier returnValueType methodName(list of parameters)
{
// Method body;
}
OOP - CoSc2051 25
Components of method declaration
• Method declaration performs three main tasks:
– It determines who may call the method (Modifier)
– It determines what the method can receive (the parameters)
– It determines how the method returns information (ReturnType)
• Method Modifiers
• Methods also can be defined using modifiers
– Method modifiers only affect how methods are used, not the
class they are defined in.
OOP - CoSc2051 26
Access modifiers
• Access modifiers used to specify Access level of
visibility of member of the class
• There are 4 types of access modifiers:
1. Default
2. Private
3. Protected
4. Public
OOP - CoSc2051 27
Public method
• Method declared as public can be accessed by any class in the same
package.
• It can also be accessed by other classes from other packages.
• This modifier gives a method the most freedom.
• For example:
OOP - CoSc2051 28
Protected modifiers
• Protected method
– A method declared as protected can only be used by classes
within the same package.
– All the subclasses beneath the class the method is defined in may
access the method unless shadowing occurs.
– Shadowing involves naming a method using a name that already
exists in a superclass above the class the method is defined in.
– For example:
protected int add(int x, int y){
int sum;
sum = x + y;
return sum;
}
OOP - CoSc2051 29
Private modifiers
• Private Method
– A method declared as private is one that can only be accessed by
the class it is defined in.
– This modifier gives a method the least amount of freedom.
– In Java as both private and final methods do not allow the
overridden functionality so no use of using both modifiers
together with same method.
OOP - CoSc2051 30
Method modifiers…
• Static Method
– A static variable is shared by all objects of the class.
– A method declared as static is one that cannot be changed.
– This type of method is also referred to as a class method, because it belongs
explicitly to a particular class.
– When an instance of the class that defines the method is created, the static method
cannot be altered.
– For this reason, a static method can refer to any other static methods or variables
by name. Limitations of static methods to keep in mind are that they cannot be
declared as final, and they cannot be overridden.
OOP - CoSc2051 32
Method modifiers…
• Final Method
– A method that is declared final is called a final method.
– We cannot override a final method.
– This means the child class can still call the final method of parent class
without any problem, but it cannot override it.
– This is because the main purpose of making a method final is to stop the
modification of the method by the sub-class.
OOP - CoSc2051 33
Method modifiers…
• Synchronized Method
– A method declared as synchronized limits it from being executed by
multiple objects at the same time.
– This is useful when you are creating Java applets and you could have
more than one thread running at the same time accessing one central
piece of data.
– If the method is static (e.g., a class method), the whole class would be
locked.
– If you just declare a particular method as synchronized, the object
containing the method would only be locked until the method finishes
executing.
OOP - CoSc2051 34
Return type of a method
Any information that is returned from a method is declared as the return type.
This assures that the information that is returned from a method call will be of
the correct type;
Otherwise, a compile-time error will be generated.
If no information will be returned by a method, the void keyword should be
placed in front of the method name.
/** Return the max of two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
OOP - CoSc2051 35
Parameter of Method
The parameter list consists of the ordered set of data elements passed to a
method.
You can pass zero, one, or multiple parameters by listing them between the
parentheses, with each type and variable name being separated by a comma.
If no parameters are passed, the parentheses should be empty.
All variables that are passed become local for that instance of the method.
public static void MyFirstMethod(String Name, int Number) {
// the String variable Name is assigned whatever is passed to it
// the integer variable Number is assigned whatever is passed to it
}
public static void MyFirstMethod() {
// Nothing is passed to it.
}
OOP - CoSc2051 36
Method body
All executable code for Java classes is contained in the body of the methods.
Unless a method is declared as abstract and native, the code for the method
is placed between a pair of curly braces.
This code can be any valid Java statements including variable declarations,
assignment statements, method calls, control statements, and so on.
OOP - CoSc2051 37
Calling a Method
Calling a method executes the code in the method.
In a method definition, you define what the method is to do.
To execute the method, you have to call or invoke it.
There are two ways to call a method, depending on whether the method
returns a value or not.
If a method returns a value, a call to the method is usually treated as a value.
For example,
int larger = max(3, 4);
If a method returns void, a call to the method must be a statement.
For example, the method println() returns void.
The following call is a statement:
System.out.println("Welcome to Java!");
OOP - CoSc2051 38
Accessing a Variable and Method
LightSwitch ls = new LightSwitch();
To access the field of an instance of an Object use instance.field
For Example: ls.on; class LightSwitch {
// field
To access the method of an instance use boolean on = true;
instance.method(arguments)
// method
For Example: ls.isOn(); boolean isOn() {
// change state
void switchs() {
on = !on;
}
}
OOP - CoSc2051 39
Object Messaging
• Software objects interact and communicate with each other by sending
messages to each other.
• When object A wants object B to perform one of B’s methods, object A
sends a message to object B.
• There are three parts of a message.
– The three parts for the message System.out.println(“Hello World”);
are:
• The object to which the message is addressed (System.out).
• The name of the method to perform (println()).
• Any parameters needed by the method (“Hello World!”).
OOP - CoSc2051 40
Parameters Passing in java
The arguments are passed by value to parameters when invoking a
method.
Parameters act as variables inside the method.
The power of a method is its ability to work with parameters.
Parameters are specified after the method name, inside the parentheses.
For example, the following method prints a message n times:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
OOP - CoSc2051 41
Parameters Passing in java
Its copying the contents of actual parameter to formal
parameter
For example, the following method prints a message n times:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
When you invoke a method with an argument, the value of the argument
is passed to the parameter. This is referred to as pass-by-value.
If the argument is a variable rather than a literal value, the value of
the variable is passed to the parameter.
The variable is not affected, regardless of the changes made to the
parameter inside the method.
OOP - CoSc2051 42
Recap
1. How is an argument passed to a method? Can the argument have the
same name as its parameter?
2. Identify and correct the errors in the following program:
public class Test
{
public static void main(String[] args)
{
nPrintln(5, "Welcome to Java!");
}
Is (g == h) ?
Answer: No
OOP - CoSc2051 44
Comparing and Identifying Objects
Two datatypes in Java: primitives and objects
Primitives: byte, short, int, long, double, float, boolean, char
== tests if two primitives have the same value.
Objects: defined in Java classes
== tests if two objects are the same object
The new keyword always constructs a new unique instance of a class.
When an instance is assigned to a variable, that variable is said to hold a
reference or point to that object
g and h hold references to two different objects that happen to have
identical state
g != h because g and h hold references to different objects
OOP - CoSc2051 45
Comparing and Identifying Objects
Java has some methods for comparison
– Java equals() Method
– Java hashCode() Method
Java equals() Method
‒ Compare the equality of two objects.
‒ The two objects are equal if they share the same memory address.
‒ Syntax: public boolean equals(Object obj)
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
OOP - CoSc2051 47
Comparing and Identifying Objects
‒ Example
//creating two instances of the Employee class
Employee emp1 = new Employee(918, "Maria");
Employee emp2 = new Employee(918, "Maria");
OOP - CoSc2051 48
The Scope of Variables
The scope of instance and static variables is the entire class, regardless
of where the variables are declared.
A variable defined inside a method is referred to as a local variable.
A class’s variables and methods can appear in any order in the class.
public class Circle {
public double findArea() {
return radius * radius * Math.PI;
}
private double radius = 1;
}
OOP - CoSc2051 50
Instance fields
LightSwitch ls = new LightSwitch();
To access the field of an instance of an Object use
class LightSwitch {
instance.field // field
For Example: ls.on; boolean on = true;
OOP - CoSc2051 52
Instance fields
.Difference between an instance variable and a class variable
Instance Variable Class Variable
• Every object will have its own copy of • Class variables are common to all
instance variables, hence changes made objects of a class, if any changes are
to these variables through one object made to these variables through object,
will not reflect in another object. it will reflect in other objects as well.
• Instance variables are declared • Class variables are declared
without static keyword. with keyword static
• Instance variables can be used only via • Class variables can be used through
object reference. either class name or object reference.
OOP - CoSc2051 53
Constructors - the Special Methods
A constructor is invoked to create an object using the new operator.
A constructor determines how an object is initialized by creating a new
instance of a class with specified parameters.
Methods and constructors actually differ in three ways.
Constructors do not have their own unique names;
they must be assigned the same name as their class name.
Constructors do not have a return type not even void.
Java assumes that the return type for a constructor is void.
Constructors are not inherited by subclasses, as a method.
OOP - CoSc2051 54
Constructors…
• In calling a constructor, you need to disregard the rules for calling methods.
– Methods are called directly;
– Constructors are called automatically by Java.
• When you create a new instance of a class, Java will automatically initialize the
object’s instance variables, and then call the class’s constructors and methods.
• Defining constructors in a class can do several things, including:
– Setting initial values of the instance variables
– Calling methods based on the initial variables
– Calling methods from other objects
– Calculating the initial properties of the object
– Creating an object that has specific properties outlined in the new argument
through overloading
OOP - CoSc2051 55
Constructor…
Components of a Constructor Declaration:
The basic format for declaring a constructor is:
[ConstructorModifier] ConstructorIdentifier([ParameterList]) [Throws] {
//ConstructorBody;
}
Both the modifier and the throws clause are optional.
The identifier is the name of the constructor;
it is important to remember that the name of the constructor
must be the same as the class name it initializes.
You may have many constructors (of the same name) in a class, as
long as each one takes a different set of parameters.
OOP - CoSc2051 56
Empty or default Constructor…
Important
•public classpoints about Constructor:
GradeBook { The same name
– A constructors must have the same name as the class its in.
private String courseName; // course name for this GradeBook
– Default constructor.
// constructor initializes courseName with String argument
• If you don't define
public GradeBook() { a constructor for a class, a default parameterless
System.out.print("Empty Constructor");
constructor is automatically created by the compiler.
} // end constructor
• The default constructor calls the default parent constructor (super())
// method to set the course name
andsetCourseName(String
public void initializes all instance variables
name)to{default value (zero for numeric
courseName = name; // store the course name
types, null for object references, and false for booleans).
} // end method setCourseName
– Default constructor is created only if there are no constructors.
// method to retrieve the course name Empty
public String define any constructor
• If you getCourseName() { for your class, no defaultconstructor
constructor is
return courseName;
automatically created.
} // end method getCourseName
}
OOP - CoSc2051 57
Parameterize Constructor …
Important
•public classpoints about Constructor:
GradeBook {
– A constructors must have the same name as the class its in.
private String courseName; // course name for this GradeBook
– Default constructor.
// constructor initializes courseName with String argument
• If you don't define name)
public GradeBook(String a constructor
{ for a class, a default parameterless
courseName = name; // initializes courseName
constructor is automatically created by the compiler.
} // end constructor
• The default constructor calls the default parent constructor (super())
// method to set the course name
andsetCourseName(String
public void initializes all instance variables
name)to{default value (zero for numeric
courseName = name; // store the course name
types, null for object references, and false for booleans).
} // end method setCourseName
– Default constructor is created only if there are no constructors.
// method to retrieve the course name
public String define any constructor
• If you getCourseName() { for your class, no default constructor is
return courseName;
automatically created.
} // end method getCourseName
}
OOP - CoSc2051 58
Constructor…
• Important points about Constructor:
– A constructors must have the same name as the class its in.
– Default constructor.
• If you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler.
• The default constructor calls the default parent constructor (super())
and initializes all instance variables to default value (zero for numeric
types, null for object references, and false for booleans).
– Default constructor is created only if there are no constructors.
• If you define any constructor for your class, no default constructor is
automatically created.
OOP - CoSc2051 59
Constructor…
• Important points about Constructor:
– Differences between methods and constructors.
• There is no return type given in a constructor signature (header).
• The value is this object itself so there is no need to indicate a
return value.
• There is no return statement in the body of the constructor.
• The first line of a constructor must either be a call on another
constructor in the same class (using this), or a call on the superclass
constructor (using super).
OOP - CoSc2051 60
The this Reference
The keyword this refers to the object itself.
It can also be used inside a constructor to invoke another
constructor of the same class.
The this keyword is the name of a reference that an object can use to
refer to itself.
A constructor can call another constructor with this(arguments)
class LightSwitch{
boolean on;
LightSwitch() {
this(true); A hidden instance variable
} can be accessed by using the
LightSwitch(boolean on){
keyword this.
this.on = on;
}
}
OOP - CoSc2051 61
The this Reference
The this keyword can be used to invoke another constructor of the
same class.
For example, you can rewrite the Circle class as follows:
public class Circle {
private double radius;
OOP - CoSc2051 62
Constructor Modifiers
• Java provides three modifiers that can be used to define constructors:
public, protected and private.
– These modifiers have the same restrictions as the modifiers used to declare standard
methods.
• Here is a summary of the guidelines for using modifiers with constructor
declarations:
– A constructor that is declared without the use of one of the modifiers may only be
called by one of the classes defined in the same package as the constructor
declaration.
– A constructor that is declared as public may be called from any class that has the
ability to access the class containing the constructor declaration.
– A constructor that is declared as protected may only be called by the subclasses of
the class that contains the constructor declaration.
– A constructor that is declared as private may only be called from within the class it
is declared in.
OOP - CoSc2051 63
Recap
1. What is the output of the following code?
public class A {
boolean x;
public static void main(String[] args) {
A a = new A();
System.out.println(a.x);
}
}
2. What is wrong in the following code?
public class Test {
private int id;
public void m1() {
this.id = 45;
}
public void m2() {
Test.id = 45;
}
}
OOP - CoSc2051 64
Destroying Objects
A destructor is a special method that gets called automatically as soon as
the life-cycle of an object is finished.
A destructor is called to de-allocate and free memory.
The following tasks get executed when a destructor is called.
Releasing the release locks
Closing all the database connections or files
Releasing all the network resources
Other Housekeeping tasks
Recovering the heap space allocated during the lifetime of an object
Destructors in Java also known as finalizers are non-deterministic.
The allocation and release of memory are implicitly handled by the
garbage collector in Java.
OOP - CoSc2051 65
Destroying Objects
Constructor vs Destructor: Difference Between A Constructor And A Destructor
Constructor Destructor
A destructor is used to delete or
A constructor is used to initialize an
destroy the objects when they are
instance of a class
no longer in use
Constructors are called when an Destructors are called when an
instance of a class is created object is destroyed or released
Memory allocation Releases the memory
Overloading is possible Overloading is not allowed
No arguments can be passed in a
They are allowed to have arguments
destructor
Java Finalize() Method
We can use the object.finalize() method which works exactly like a destructor
in Java.
OOP - CoSc2051 66
Encapsulation
Encapsulation refers to wrapping up of data under a single unit.
It is the mechanism that binds code and the data it manipulates.
Another way to think about encapsulation is, it is a protective shield that
prevents the data from being accessed by the code outside this shield.
In this, the variables or data of a class is hidden from any other class and can
be accessed only through any member function of own class in which they
are declared.
Encapsulation in Java can be achieved by:
1. Declaring the variables of a class as private.
2. Providing public setter and getter methods to modify and view the
variables values.
OOP - CoSc2051 67
Encapsulation …
public class Student {
OOP - CoSc2051 68
Enumerated Types
• Enumerated type is which defines a set of constants represented
as unique identifiers.
• Like classes, all enum types are reference types.
• An enum type is declared with an enum declaration.
• An enum is a comma-separated list of enum constants.
• An enum declaration may optionally include other components of
traditional classes, such as constructors, fields and methods.
OOP - CoSc2051 69
Enumerated Types
• Each enum declaration declares an enum class that satisfies the
following criteria:
OOP - CoSc2051 72
Recap (10% Worth) Assignment
7.13 Exercise
(Employee Class) Create an Employee class that includes a first name
(type String), a last name (type String) and a monthly salary (double)
instance variable.
Provide a constructor that initializes the three instance variables.
Provide a set and a get method for each instance variable.
If the monthly salary is not positive, do not set its value.
Write a test application named EmployeeTest that demonstrates class
Employee’s capabilities.
Create two Employee objects and display each object’s yearly salary.
Then give each Employee a 10% raise and display each Employee’s yearly
salary again.
OOP - CoSc2051 73
Recap (10% Worth) Assignment
7.13 Exercise 2
(Student Class) Create an Student class that includes a first name (type
String) and a Roll Number (type String) instance variable and info method.
Make if default constructor is called display Not Registered.
Make if parameterized constructor is called displays their info.
Provide a set and a get method for each instance variable.
If the default is used set its value to empty.
If the parameterized is used set its value accordingly.
OOP - CoSc2051 74
Bye
OOP - CoSc2051 75