You are on page 1of 62

Bahir Dar University ባሕር ዳር ዩኒቨርሲቲ

Bahir Dar Institute of Technology ባሕር ዳር ቴክኖሎጂ ኢንስቲትዩት


Faculty of Computing ኮምፒዩትንግ ፋኩሊት

Object Oriented Programming

Course Code: SEng2071


Target Group: 2nd Year Software Engineering
Instructor: Haileyesus D.
Object Oriented Programming
CHAPTER TWO OBJECTS AND CLASSES

Compiled by : Haileyesus Demissie Object Oriented Programming 2


Chapter Outline
Class
Objects
Constructors
Creating Objects
Access specifiers/ Modifiers
this keyword
Accessors and Mutators
Static and instance members

Compiled by : Haileyesus Demissie Object Oriented Programming 3


Object
You can look around you now and see many examples of real-
world objects: a desk, computer, chair, person, students, class
rooms, chalk, etc.
Real world objects share two characteristics:
State
Behavior
Example: Object  Student
State  name, age, sex, id, year of study, etc
Behavior  studying, register, withdraw

Compiled by : Haileyesus Demissie Object Oriented Programming 4


Object
A real world object may be represented in software.
Different fields/variables represent the state of the object.
Various methods/functions represent the behavior of the object.

Example: Object Type Light


Variable  boolean switchState;
Method  void turnSwitch(boolean on){…}

Compiled by : Haileyesus Demissie Object Oriented Programming 5


Properties of Object
Each object has a type/class.
An object is an instance of a class/type. We write new
classes to define new types of objects.
A particular object resembles other objects of its type. A few
variables of an object may be shared by all objects of the same
type.
An Object can be mutable (has changing state) or immutable
(its methods do not change its state).
Objects can inherit properties, both state and behavior, from
other objects.
Compiled by : Haileyesus Demissie Object Oriented Programming 6
Class
Class is a user defined data types to create objects.
Class is a blueprint from which individual objects are
created.
Collection of object is called a class.
A class can contains:
♠ Methods
♠ Variables
♠ Constructors

Compiled by : Haileyesus Demissie Object Oriented Programming 7


Class
Class syntax:
package <package_name>
import <other_package>
public class <class_name>{
<fields or variables>;
<constructors methods>{}
<other methods>{}
}

Compiled by : Haileyesus Demissie Object Oriented Programming 8


Class
Example
public class Student {
String name;
int id;
String department;
public Student(){…}
void register(){…}
void withdraw(){…}
}
Compiled by : Haileyesus Demissie Object Oriented Programming 9
Class
If there is a public class in a file, the name of the file must
match the name of the public Class Name.
Example: a class declared as public class Student{} must be in
a source code file named Student.java
There can be only one public class per source file.
A file can have more than one non public class.

Compiled by : Haileyesus Demissie Object Oriented Programming 10


Class Variable Types
A class can contain any of the following variable types.
♠ Local variables
♠ Instance variables
♠ Class variables

Local Variables:
Defined inside methods, constructors or blocks
The variable will be declared and initialized within the method
The variable will be destroyed when the method has completed.

Compiled by : Haileyesus Demissie Object Oriented Programming 11


Class Variable Types
Instance variables: instance variables are variables within a class but
outside any method.
These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.

Class variables: Class variables are variables declared within a class,


outside any method, with the static keyword.

Compiled by : Haileyesus Demissie Object Oriented Programming 12


Constructors
Constructors: are functions called during the creation (instantiation)
of an object.
Every class has a constructor.
If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be
invoked.
The main rule of constructors is that they should have the same name
as the class.

Compiled by : Haileyesus Demissie Object Oriented Programming 13


Constructors
Constructors can take argument.
A class can have more than one constructor. Which means it is
possible to declare more than one constructor in a class.
Constructors have no return type.
Example:
Default constructor
public class Student{
public Student(){ }
Constructor with
public Student(String name){ } argument

}
Compiled by : Haileyesus Demissie Object Oriented Programming 14
Types of Constructor
There are two types of constructors in Java:
Default constructor (No argument constructor)
Parameterized constructor

Compiled by : Haileyesus Demissie Object Oriented Programming 15


Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.
Syntax of default constructor: <class_name> () {}

class Bike {
Bike(){
System.out.println("Bike is created");
}
public static void main(String[] args){
Bike b1 = new Bike();
}
}
Compiled by : Haileyesus Demissie Object Oriented Programming 16
Default Constructor
If there is no constructor in a
class, compiler automatically
creates a default constructor.
The default constructor is
used to provide the default
values to the object like 0,
null, etc., depending on the
data type.

Compiled by : Haileyesus Demissie Object Oriented Programming 17


Parametrized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.

Compiled by : Haileyesus Demissie Object Oriented Programming 18


Parametrized Constructor

Compiled by : Haileyesus Demissie Object Oriented Programming 19


Constructor Overloading
Constructor overloading in Java is a technique of having more than
one constructor with different parameter lists.
They are arranged in a way that each constructor performs a different
task.
They are differentiated by the compiler by the number of parameters
in the list and their types.

Compiled by : Haileyesus Demissie Object Oriented Programming 20


Constructor Overloading

Compiled by : Haileyesus Demissie Object Oriented Programming 21


Method Vs. Constructor

Compiled by : Haileyesus Demissie Object Oriented Programming 22


Creating Objects
As mentioned previously, a class provides the blueprints for
objects. So basically, an object is created from a class.
In Java, the new keyword is used to create new objects.
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.
♠ Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

♠ Example: Students student=new Students();

Compiled by : Haileyesus Demissie Object Oriented Programming 23


Creating Objects
Example:

public class Student{


public Student(){}
public static void main(String[] args){
Student st = new Student();
}
}
Compiled by : Haileyesus Demissie Object Oriented Programming 24
Creating Objects
Example:
public class Student{
public Student(String name){
System.out.println(name);
}
public static void main(String[] args){
Student st = new Student(“Temesgen”);
}
}
Compiled by : Haileyesus Demissie Object Oriented Programming 25
Accessing Instance Variables and Methods
Java use dot(.) operator to access the object’s instance
variables and methods.
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

Compiled by : Haileyesus Demissie Object Oriented Programming 26


Accessing Instance Variables and Methods

Compiled by : Haileyesus Demissie Object Oriented Programming 27


Package
In simple words, it is a way of categorizing the classes and interfaces.
When developing applications in Java, hundreds of classes and
interfaces will be written, therefore categorizing these classes is a
must as well as makes life much easier.
Packaging the classes promotes code reuse, maintainability,
and an object oriented principles of encapsulation and
modularity.
The package statement includes package keyword followed by
the package path delimited with period.
Example: package student.ugstudent.oop
Compiled by : Haileyesus Demissie Object Oriented Programming 28
Package
If the class is defined inside a package, then the package
statement should be the first statement in the source file.
Package statements have the following attribute:
♠Package statements are optional to a source file
♠Package statements are limited to one per source file
♠Package names equate to directory structure
♠Package name should be lowercase.

Compiled by : Haileyesus Demissie Object Oriented Programming 29


Import Statement
Import statement is a way of giving the proper location for the
compiler to find particular class.
Allow you to include the source file from other classes into a source
file at compile time.
To import classes from other packages into your source file, use
import statement.
The import statement includes import keyword followed by the
package path delimited with periods ending with a class name or an
asterisk(*)

Compiled by : Haileyesus Demissie Object Oriented Programming 30


Import Statement
Example:
import all of the classes from
the package java.net

Import java.net.*;

imports only the


FirstExercise from
Import scee.cse.oop.FirstExercise; the package
scee.cse.oop

Compiled by : Haileyesus Demissie Object Oriented Programming 31


Import Statement
If import statements are present, then they must be written between
the package statement and the class declaration.
If there are no package statements, then the import statement should
be the first line in the source file.

Compiled by : Haileyesus Demissie Object Oriented Programming 32


How to Create a Reference to an Object
Java language uses pass-by-value for all assignment
operation.
For java objects, the value of an object reference is the
memory pointer to the instance of the object created.
In java, you can obtain a reference to an object in three
ways:
♠Using new operation
♠Reference by assignment
♠Cloning an object
Compiled by : Haileyesus Demissie Object Oriented Programming 33
Using new Operation
The new operation instantiates an object of a particular class, and
returns a reference to it.
This reference is a handle to the location where the object resides in
memory.
Example:
Student std1 = new Student();
Student std2 = new Student();
std1 ≠ std2

Compiled by : Haileyesus Demissie Object Oriented Programming 34


Reference by Assignment
The reference to an existing reference obtained by assignment is just
a duplicate reference to the object (and not to a copy of the object).
Example: Student std2 = new Student();
Student std3 = std2;

std3 Student std2

After the assignment, the value of std3 is the same as std2. Both
reference the same object Student.

Compiled by : Haileyesus Demissie Object Oriented Programming 35


Cloning an Object
The reference that is returned by cloning an object is a new reference
to a copy of the object.
Once an object is cloned, two copies of the object exist with
independent references.
Changing one object does not automatically change the other.
Example:
Student std3=std1.clone();

♠ std3 ≠ std1

Compiled by : Haileyesus Demissie Object Oriented Programming 36


Object Passes as a Parameter
When you pass an object variable into a method, you must keep in
mind that you're passing the object reference, and not the actual
object itself.
A reference variable holds bits that represent (to the underlying VM)
a way to get to a specific object in memory.
You aren't even passing the actual reference variable, but rather a
copy of the reference variable.
In other words, both the caller and the called method will now have
identical copies of the reference, and thus both will refer to the same
exact (not a copy) object on the heap.

Compiled by : Haileyesus Demissie Object Oriented Programming 37


Object Passes as a Parameter
However, when we need to pass objects into a method we don’t have
to use the new keywords inside the method.

Compiled by : Haileyesus Demissie Object Oriented Programming 38


Accessors and Mutators
When a class have fields (instance variables), it is a good design to
make all instance variables private and to provide methods for storing
and retrieving the data fields. These methods are known as accessors
and mutators. They are sometimes called “getters” and “setters”.
This means external classes have no way to access these variables.

Compiled by : Haileyesus Demissie Object Oriented Programming 39


Accessors and Mutators
Naming Convention for getter and setter
The naming scheme of setter and getter should follow Java bean
naming convention as follows: getXXX() and setXXX(),
where XXX is the name of the variable
When creating a getter, the name should start with a lowercase ‘get’,
followed by the variable name with no spaces and the first letter
capitalized.
The one exception to this is when a boolean value is returned. In this
case, instead of using ‘get’, ‘is’ is used with the same rules being
applied to the variable name.

Compiled by : Haileyesus Demissie Object Oriented Programming 40


Accessors and Mutators
A setter should start with the word ‘set’, followed by the variable name with the
first letter capitalized.
Example: private int number;
private boolean passed;
The appropriate getter and setter methods for the above variable is:
public int getNumber(){
return number;
}
public void setNumber(int n){
number=n;
}
public boolean isPassed(){
return passed;
}

Compiled by : Haileyesus Demissie Object Oriented Programming 41


Accessors and Mutators
Example: lets add getter and setter method to Student class

Compiled by : Haileyesus Demissie Object Oriented Programming 42


this Keyword
The this keyword allows the compiler to distinguish between the field name of
the class and the parameter name being passed in as argument.

Usage of this keyword


It can be used to refer instance variable of current class
It can be used to invoke or initiate current class constructor
It can be passed as an argument in the method call
It can be passed as argument in the constructor call
It can be used to return the current class instance

Compiled by : Haileyesus Demissie Object Oriented Programming 43


this Keyword

a and b have a default value of int: 0 Output

Assign the values for itself

Compiled by : Haileyesus Demissie Object Oriented Programming 44


this Keyword

Output

Assign the value of local variables(a&b)


to instance variable(a&b)

Compiled by : Haileyesus Demissie Object Oriented Programming 45


Access Modifiers
There are two types of modifiers in java: access
modifiers and non-access modifiers.
Access modifiers in Java helps to restrict the scope of a class,
constructor, variable, method or data member.
There are four types of access modifiers available in java:
♠Default – No keyword required
♠Private
♠Protected
♠Public
Compiled by : Haileyesus Demissie Object Oriented Programming 46
Access Modifiers

Compiled by : Haileyesus Demissie Object Oriented Programming 47


Default
Default: When no access modifier is specified for a class , method or
data member – It is said to be having the default access modifier by
default.
The data members, class or methods which are not declared using
any access modifiers i.e. having default access modifier are
accessible only within the same package.

Compiled by : Haileyesus Demissie Object Oriented Programming 48


Default

Output: Compile time Error


Compiled by : Haileyesus Demissie Object Oriented Programming 49
Private
Private: The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the
class in which they are declared.
Any other class of same package will not be able to access these members.
Classes or interface can not be declared as private.
If you make any class constructor private, you cannot create the instance of that
class from outside the class.

Compiled by : Haileyesus Demissie Object Oriented Programming 50


Private
Both classes are within the same package p1

Output

Compiled by : Haileyesus Demissie Object Oriented Programming 51


Protected
Protected: The protected access modifier is specified using the
keyword protected.
The methods or data members declared as protected are accessible within same
package or sub classes in different package.
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.

Compiled by : Haileyesus Demissie Object Oriented Programming 52


Protected

Output
Compiled by : Haileyesus Demissie Object Oriented Programming 53
Public
Public: The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access
modifiers.
Classes, methods or data members which are declared as public are accessible
from every where in the program.
There is no restriction on the scope of a public data members.

Compiled by : Haileyesus Demissie Object Oriented Programming 54


Public

Output
Compiled by : Haileyesus Demissie Object Oriented Programming 55
Static and Instance Variables
Static Variables
Static variable in Java is variable which belongs to the class and
initialized only once at the start of the execution.
It is a variable which belongs to the class and not to object(instance ).
A single copy to be shared by all instances of the class.
A static variable can be accessed directly by the class name and
doesn’t need any object

Compiled by : Haileyesus Demissie Object Oriented Programming 56


Static and Instance Variables
Instance Variable
A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific
and is not shared among instances.

Compiled by : Haileyesus Demissie Object Oriented Programming 57


Static and Instance Variables

public class VariableExample {


int myVariable;
static int data = 30;

public static void main(String args[]){


VariableExample obj = new VariableExample();
System.out.println("Value of instance variable: "+ obj.myVariable);
System.out.println("Value of static variable: "+ VariableExample.data);
}
}

Compiled by : Haileyesus Demissie Object Oriented Programming 58


Static and Instance Methods
Instance Method
Instance method are methods which require an object of its class to
be created before it can be called.
To invoke a instance method, we have to create an Object of the class
in within which it defined.

Compiled by : Haileyesus Demissie Object Oriented Programming 59


Static and Instance Methods

class Foo { class GFG {


String name = ""; public static void main(String[] args)
public void geek(String name) { {
this.name = name; Foo ob = new Foo();
} ob.geek(“Ethiopia");
} System.out.println(ob.name);
}
}

Compiled by : Haileyesus Demissie Object Oriented Programming 60


Static and Instance Methods
Static Method
Static method in Java is a method which belongs to the class and not
to the object. A static method can access only static data. It cannot
access non-static data (instance variables).
A static method can call only other static methods and can not call a
non-static method from it.
A static method can be accessed directly by the class name and
doesn’t need any object. They are referenced by the class name
itself or reference to the Object of that class.
A static method cannot refer to “this” or “super” keywords in anyway.
Compiled by : Haileyesus Demissie Object Oriented Programming 61
Static and Instance Methods

class Geek { class GFG {


public static String geekName = ""; public static void main(String[] args)
{
public static void geek(String name) Geek.geek(“Abebe");
{ System.out.println(Geek.geekName);
geekName = name; Geek obj = new Geek();
} obj.geek(“Kebede");
} System.out.println(obj.geekName);
}
}

Compiled by : Haileyesus Demissie Object Oriented Programming 62

You might also like