Chapter2-Classes and Objects

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

OOP: Chapter 2- Classes and Objects

1. Introduction
In procedural programming, data and operations on the data are separate, and this methodology
requires sending data to methods. Object-oriented programming places data and the operations
that pertain to them within a single entity called an object; this approach solves many of the
problems inherent in procedural programming. The object-oriented programming approach
organizes programs in a way that mirrors the real world, in which all objects are associated with
both attributes and activities. Using objects improves software reusability and makes programs
easier to develop and easier to maintain.

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,
and even a loan can all be viewed as objects. An object has a unique identity, state, and behaviors.
Programming in Java involves thinking in terms of objects; a Java program can be viewed as a
collection of cooperating objects.

2. Object and Class in Java


An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car
etc. It can be physical or logical (tangible and intangible). The example of intangible object is
banking system.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an
Object Object
object such as deposit, withdraw etc.
 identity: Object identity is typically implemented via
a unique ID. The value of the ID is not visible to the
external user. But, it is used internally by the JVM to
identify each object uniquely.
Example,

object state behavior


dog color, isHungry eat, bark

grade book grades mean, median

light on/off switch

A circle object, for example, has a data field, radius, which is the property that characterizes
a circle. One behavior of a circle is that its area can be computed using the method getArea().
Object Definitions:
 Object is a real world entity.
 Object is a run time entity.
 Object is an entity which has state and behavior.
 Object is an instance of a class.

University of Gondar, Department of Computer Science Page 1


OOP: Chapter 2- Classes and Objects

Class in Java
Objects of the same type are defined using a common class. A class is a group of objects which
have common properties. It is a template or blueprint from which objects are created. It is a logical
entity. It can't be physical. A class in Java can contain:

 fields
 methods
 constructors
 blocks
 nested class and interface

A class is a template that defines what an object's data and methods will be. 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.

Syntax to declare a class:


[ClassModifiers] class <class_name>{
field;
method;
}
A class can be visualized as a three-compartment box:
 Name (or identity): identifies the class.
 Variables (or attribute, state, field): contains the static attributes of the class.
 Methods (or behaviour, function, operation): contains the dynamic behaviours of the
class

This notation, as shown in the Figure above, is called a UML ((Unified Modeling Language) class
diagram, or simply a class diagram.

A Java class uses variables to define data fields and methods to define behaviors. Additionally, a
class provides methods of a special type, known as constructors, which are invoked when a new
object is created. A constructor is a special kind of method. A constructor can perform any action,
but constructors are designed to perform initializing actions, such as initializing the data fields of
objects. The following figure shows an example of the class for Circle objects.

University of Gondar, Department of Computer Science Page 2


OOP: Chapter 2- Classes and Objects

Classes and objects can be represented using UML notation

In the class diagram, the data field is denoted as: dataFieldName: dataFieldType
The constructor is denoted as: ClassName(parameterName: parameterType)
The method is denoted as: methodName(parameterName: parameterType): returnType

Instance variable in Java: A variable which is created inside the class but outside the method, is
known as instance variable. Instance variable doesn't get memory at compile time. It gets memory
at run time when object (instance) is created. That is why, it is known as instance variable.
Method in Java: In java, a method is like function i.e. used to expose behavior of an object.
new keyword in Java: The new keyword is used to allocate memory at run time. All objects get
memory in Heap memory area.

3. Constructing Objects Using Constructors


A constructor is invoked to create an object using the new operator. Constructors are a special kind
of method. They have three peculiarities:
 A constructor must have the same name as the class itself.
 Constructors do not have a return type - not even void.
 Constructors are invoked using the new operator when an object is created. Constructors
play the role of initializing objects.
The constructor has exactly the same name as its defining class. Like regular methods, constructors
can be overloaded (i.e., multiple constructors can have the same name but different signatures),
making it easy to construct objects with different initial data values.

Constructors are used to construct objects. To construct an object from a class, invoke a
constructor of the class using the new operator, as follows: new ClassName(arguments);

For example, new Circle() creates an object of the Circle class using the first constructor
defined in the Circle class, and new Circle(25) creates an object using the second constructor
defined in the Circle class.

A class normally provides a constructor without arguments (e.g., Circle()). Such a constructor is
referred to as a no-arg or no-argument constructor.

University of Gondar, Department of Computer Science Page 3


OOP: Chapter 2- Classes and Objects

A class may be defined without constructors. In this case, a public no-arg constructor with an
empty body is implicitly defined in the class. This constructor, called a default constructor, is
provided automatically only if no constructors are explicitly defined in the class.

4. Accessing Objects via Reference Variables


Newly created objects are allocated in the memory. How can they be accessed?
a. Reference Variables and Reference Types
Objects are accessed via object reference variables, which contain references to the objects.
Such variables are declared using the following syntax: ClassName objectRefVar;
A class defines a type, known as a reference type. Any variable of the class type can reference to
an instance of the class. The following statement declares the variable myCircle to be of the
Circle type: Circle myCircle;
The variable myCircle can reference a Circle object. The next statement creates an object and
assigns its reference to myCircle. myCircle = new Circle();
Using the syntax shown below, you can write one statement that combines the declaration of an
object reference variable, the creation of an object, and the assigning of an object reference to the
variable.
ClassName objectRefVar = new ClassName();
Here is an example:
Circle myCircle = new Circle();
The variable myCircle holds a reference to a Circle object.
Note
Arrays are treated as objects in Java. Arrays are created using the new operator. An array variable
is actually a variable that contains a reference to an array.
b. Accessing an Object's Data and Methods
After an object is created, its data can be accessed and its methods invoked using the dot operator
(.), also known as the object member access operator:
 objectRefVar.dataField references a data field in the object.
 objectRefVar.method(arguments) invokes a method on the object.
For example, myCircle.radius references the radius in myCircle, and myCircle.getArea()
invokes the getArea method on myCircle. Methods are invoked as operations on objects.
The data field radius is referred to as an instance variable because it is dependent on a specific
instance.
For the same reason, the method getArea is referred to as an instance method, because you can
only invoke it on a specific instance. The object on which an instance method is invoked is
referred to as a calling object.
Note
Most of the time, you create an object and assign it to a variable. Later you can use the variable to
reference the object. Occasionally, an object does not need to be referenced later. In this case, you
can create an object without explicitly assigning it to a variable, as shown below:
new Circle(); or System.out.println("Area is " + new Circle(5).getArea());
The former statement creates a Circle object. The latter statement creates a
Circle object and invokes its getArea method to return its area. An object created in this way is
known as an anonymous object.

University of Gondar, Department of Computer Science Page 4


OOP: Chapter 2- Classes and Objects

5. Example: Defining Classes and Creating Objects


Classes are definitions for objects and objects are created from classes.
Example1: main within class
In this example, we have created a Student class that have two data members : id and name. We
are creating the object of the Student class by new keyword and printing the objects value. Here,
we are creating main() method inside the class.

public class Student{


int id;//field or data member or instance variable Program Output
String name;
0
public static void main(String args[]){
null

Student stud=new Student();//creating an object of Student


System.out.println(stud.id);//accessing member through reference variable
System.out.println(stud.name);
}
}
Example2: main outside class
In real time development, we create classes and use it from another class. It is a better approach than
previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different java files or single java file. If you define multiple classes
in a single java source file, it is a good idea to save the file name with the class name which has main()
method.
class Student{
int id;
String name;
} Program Output
public class TestStudent{
0
public static void main(String args[]){
null
Student stud =new Student();
System.out.println(stud.id);
System.out.println(stud.name);
}
}

The program contains two classes. The second of these, TestStudent, is the main class. Its sole
purpose is to test the first class, Student. When you run the program, the Java runtime system
invokes the main method in the main class.
You can put the two classes into one file, but only one class in the file can be a public class.

University of Gondar, Department of Computer Science Page 5


OOP: Chapter 2- Classes and Objects

Furthermore, the public class must have the same name as the file name. Therefore, the file name
is TestStudent.java, since TestStudent is public. Each class in the source code is compiled into
a .class file. When you compile TestStudent.java, two class files TestStudent.class and
Student.class are generated.
Example3: Initialization through reference
Initializing object simply means storing data into object. Let's see a simple example where we are
going to initialize object through reference variable.
class Student{
int id;
String name;
}
Program Output
public class TestStudent1{
public static void main(String args[]){ 1711 Menberu
Student stud=new Student();
stud.id=1711;
stud.name="Menberu";
System.out.println(stud.id+" "+ stud.name);//printing members with a white space
}
}
Example4: We can also create multiple objects and store information in it through reference
variable.
class Student{
int id;
String name;
} Program Output
public class TestStudent2{
public static void main(String args[]){
1711 Menberu
1890 Yasin
//Creating objects
Student stud1=new Student();
Student stud2=new Student();
//Initializing objects
stud1.id=1711;
stud1.name="Menberu";
stud2.id=1890;
stud2.name="Yasin";
//Printing data
System.out.println(stud1.id+" "+stud1.name);
System.out.println(stud2.id+" "+stud2.name);
} }

University of Gondar, Department of Computer Science Page 6


OOP: Chapter 2- Classes and Objects

Example5: Initialization through method


In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects
by invoking the displayInformation() method.
class Student{
int id;
String name;
void insertRecord(int i, String n){
id=i;
name=n;
}
void displayInformation(){System.out.println(id+" "+name);}
}
public class TestStudent3{
public static void main(String args[]){
Student stud1=new Student(); Program Output
Student stud2=new Student();
1628 Hiwot
stud1.insertRecord(1628,"Hiwot"); 1619 Haymanot
stud2.insertRecord(1619,"Haymanot");
stud1.displayInformation();
stud2.displayInformation();

}
}

Example6: Initialization through parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

public class Student{


int id;
String name;
Student(int i,String n){
id = i;
name = n;
Program Output
}
void display(){System.out.println(id+" "+name);} 1650 Kenu
public static void main(String args[]){ 1547 Fasika
Student stud1 = new Student(1650,"Kenu");

University of Gondar, Department of Computer Science Page 7


OOP: Chapter 2- Classes and Objects

Student stud2 = new Student(1547,"Fasika");


stud1.display();
stud2.display();
}
}

Example7: Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists. The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type
public class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n; Program Output
age=a;
} 1900 Yibeltal 0
1861 Tirusew 22
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student stud1 = new Student(1900,"Yibeltal");
Student stud2 = new Student5(1861,"Tirusew",22);
stud1.display();
stud2.display();
}
}

6. Static Variables, Constants, and Methods


The data field id in the student class from the previous examples is known as an instance variable.
An instance variable is tied to a specific instance of the class; it is not shared among objects of the
same class. For example, suppose that you create the following objects:
Student stud1 = new Student();
Student stud2 = new Student(1156);

University of Gondar, Department of Computer Science Page 8


OOP: Chapter 2- Classes and Objects

The id in stud1 is independent of the id in stud2, and is stored in a different memory location.
Changes made to stud1's id do not affect stud2's id, and vice versa.

If you want all the instances of a class to share data, use static variables. Static variables store
values for the variables in a common memory location. Because of this common location, all
objects of the same class are affected if one object changes the value of a static variable. Java
supports static methods as well as static variables. Static methods can be called without creating
an instance of the class.

If you declare any variable as static, it is known static variable.


 The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees, faculty name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
 Static variable makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
public class Student{
int id;
String name;
String faculty="Informatics";
}
Suppose there are 600 students in your faculty, now all instance data members will get memory
each time when object is created. All student have its unique id and name so instance data member
is good. Here, faculty refers to the common property of all objects. If we make it static, this field
will get memory only once.

Example of static variable


//Program of static variable
public class Student{
int id;
String name;
static String faculty ="Informatics";

Student(int i,String n){


id = i;
Program Output
name = n; 1736 Mulu Informatics
} 1727 Mintamir Informatics
void display (){System.out.println(id+" "+name+" "+faculty);}

public static void main(String args[]){


Student stud1 = new Student(1736,"Mulu");
Student stud2 = new Student(1727,"Mintamir");

University of Gondar, Department of Computer Science Page 9


OOP: Chapter 2- Classes and Objects

stud1.display();
stud2.display();
}
}

Constants in a class are shared by all objects of the class. Thus, constants should be declared final
static. For example, the constant PI in the Math class is defined as:
final static double PI = 3.14159265358979323846;

Static methods
If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 Static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects (static field).

public class Student{


int id;
String name;
static String faculty = "Informatics";

static void change(){


faculty = "Technology";
}

Student(int i, String n){


id = i;
name = n;
}

void display (){System.out.println(id+" "+name+" "+faculty);}

public static void main(String args[]){


Student.change();

Student stud1 = new Student (1703,"Melkamu"); Program Output


Student stud2 = new Student (1891,"Yawekal");
Student stud3 = new Student (1930,"Zelalem");
1703 Melkamu Technology
stud1.display();
1891 Yawekal Technology
stud2.display(); 1930 Zelalem Technology
stud3.display();
}
}

University of Gondar, Department of Computer Science Page 10


OOP: Chapter 2- Classes and Objects

An instance method can invoke an instance or static method and access an instance or static data
field. A static method can invoke a static method and access a static data field. However, a static
method cannot invoke an instance method or access an instance data field, since static methods
and static data fields don’t belong to a particular object. The relationship between static and
instance members is summarized in the following diagram:

For example, the following code is wrong.

public class A {
int i = 5;
static int k = 2;

public static void main(String[] args) {


int j=i; // Wrong because i is an instance variable
m1(); // Wrong because m1() is an instance method
}
public void m1() {
// Correct since instance and static variables and methods
// can be used in an instance method
i = i + k + m2(i, k);
}

public static int m2(int i, int j) {


return (int)(Math.pow(i, j));
}
}
Note that if you replace the preceding code with the following new code, the program would be
fine, because the instance data field i and method m1 are now accessed from an object a
public class A {
int i = 5;
static int k = 2;

public static void main(String[] args) {


A a = new A();
int j=a.i; // OK, a.i accesses the object's instance variable
a.m1()// OK. a.m1() invokes the object's instance method
}

public void m1() {


i = i + k + m2(i, k);
}

public static int m2(int i, int j) {


return (int)(Math.pow(i, j));
}}

University of Gondar, Department of Computer Science Page 11


OOP: Chapter 2- Classes and Objects

7. Visibility Modifiers
Visibility modifiers can be used to specify the visibility of a class and its members. Java provides
a number of visibility modifiers to help you set the level of access you want for classes as well as
the fields, methods and constructors in your classes.

You can use the public visibility modifier for classes, methods, and data fields to denote that
they can be accessed from any other classes. If no visibility modifier is used, then by default the
classes, methods, and data fields are accessible by any class in the same package. This is known
as package-private or package-access. For example, as shown in the figure below, C1 can be
accessed from C2 but not from C3.

In addition to the public and default visibility modifiers, Java provides the private and protected
modifiers for class members.

The private modifier makes methods and data fields accessible only from within its own class.
For example the figure below illustrates how a public, default, and private data field or method in
class C1 can be accessed from a class C2 in the same package and from a class C3 in a different
package.

The private modifier restricts access to its defining class, the default modifier restricts access to a
package, and the public modifier enables unrestricted access .

The protected fields or methods cannot be used for classes in different package. The protected
modifier will be introduced in the next chapter.

8. This keyword
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.
a. this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters, this keyword resolves the problem of ambiguity.

University of Gondar, Department of Computer Science Page 12


OOP: Chapter 2- Classes and Objects

Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int id;
String name;
float fee;
Student(int id,String name,float fee){
id=id;
name=name;
fee=fee;
}
void display(){System.out.println(id+" "+name+" "+fee);}
}
Program Output
public class TestThis{
public static void main(String args[]){ 0 null 0.0
Student stud1=new Student(92,"Semira",5000f); 0 null 0.0
Student stud2=new Student(910,"Abdu",6000f);
stud1.display();
stud2.display();
}}

In the above example, parameters (formal arguments) and instance variables are same. So, we are
using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


class Student{
int id;
String name;
float fee;
Student(int id,String name,float fee){
this.id=id;
Program Output
this.name=name;
this.fee=fee; 92 Semira 5000
} 910 Abdu 6000
void display(){System.out.println(id+" "+name+" "+fee);}
}
public class TestThis1{
public static void main(String args[]){

University of Gondar, Department of Computer Science Page 13


OOP: Chapter 2- Classes and Objects

Student stud1=new Student(92,"Semira",5000f);


Student stud2=new Student(910,"Abdu",6000f);
stud1.display();
stud2.display();
}}
If local variables (formal arguments) and instance variables are different, there is no need to use
this keyword.
b. this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example

class A{
void m(){System.out.println("hello m");}
void n(){ System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
public class TestThis2{
Program Output
public static void main(String args[]){ hello n
A a=new A(); hello m
a.n();
}}

c. this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.

Example: Calling default constructor from parameterized constructor:

class A{
A(){System.out.println("hello a");} Program Output
A(int x){
this(); hello a
10
System.out.println(x);
} }

University of Gondar, Department of Computer Science Page 14


OOP: Chapter 2- Classes and Objects

public class TestThis2{


public static void main(String args[]){
A a=new A(10);
}}

9. Getters and Setters Methods


A private data field cannot be accessed by an object through a direct reference outside the class
that defines the private field. But often a client needs to retrieve and modify a data field. To make
a private data field accessible, provide a get method to return the value of the data field. To enable
a private data field to be updated, provide a set method to set a new value.

In Java, getter and setter are two conventional methods that are used for retrieving and updating
value of a variable. The following code is an example of simple class with a private variable and
a couple of getter/setter methods:

public class SimpleGetterAndSetter {


private int number;

public int getNumber() {


return this.number;
}

public void setNumber(int num) {


this.number = num;
}
}
The class declares a private variable, number. Since number is private, code from outside this
class cannot access the variable directly, like this:
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.number = 10; // compile error, since number is private
int num = obj.number; // same as above

Instead, the outside code have to invoke the getter, getNumber() and the setter, setNumber() in
order to read or update the variable, for example:
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.setNumber(10); // OK
int num = obj.getNumber(); // fine

Note:
A setter is a method that updates value of a variable. And a getter is a method that reads value of
a variable. The naming scheme of setter and getter should follow naming convention as follows:
getXXX() and setXXX(), where XXX is name of the variable.

University of Gondar, Department of Computer Science Page 15

You might also like