Chapter2-Classes and Objects
Chapter2-Classes and Objects
Chapter2-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.
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.
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.
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.
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.
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.
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.
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.
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);
} }
}
}
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.
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).
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:
public class A {
int i = 5;
static int k = 2;
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.
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.
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();
}}
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.
class A{
A(){System.out.println("hello a");} Program Output
A(int x){
this(); hello a
10
System.out.println(x);
} }
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:
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.