UNIT 2
UNIT 2
Contents
2.0. Aims and Objectives
2.1. Classes and Objects
2.2. Reference variables Vs Primitive variables
2.3. Constructors
2.4. Java Declaration and Access Modifiers
2.5. The ‘this’ keyword in Java
2.6. Summary
2.7. Model Examination Questions
This unit discusses the basics of OOP such as objects and classes, reference and primitive
variables, explaining default and parameterized constructors. It also describes access
modifiers in detail.
After you have studied this unit, you will be able to:
1
2.1. INTRODUCTION TO CLASSES AND OBJECTS
Classes and Objects are basic concepts of Object Oriented Programming which revolve
around the real life entities. In an objected oriented model, the focus is on data (contained
in objects) and not on the code that manipulates the data. A class contains instance
variables, constructors and methods. We instantiate (create) objects from these classes by
invoking (calling) the constructors. Each object created from a class has a copy of the
instance variables. Each object manipulates its instance variables independently using the
methods of the class. While variables represent an object, the methods help in modification
of these variables and accomplishment of tasks.
Object oriented model of programming helps to simulate real world objects in a better way.
Let's discuss how this is done by considering a 'Car 'class as an example. The class can have
instance variables such as current Speed, quantityOfPetrol, and so on. We can provide
methods such as startCar(), stopCar(), chageSpeed() and so on. Some of these methods do
not require any additional information while a few others do require. For instance,
startCar() and stopCar() doesn't require any additional information while changeSpeed()
requires the speed to which the car is to be raced. This information that is to be passed is
known as an argument. In conclusion, we have designed the 'Car' class and we are now
capable of building a number of Car objects from them such as 'Car1', 'Car2' and so on. Each
of these objects function independently from each other by maintaining their own sets of
variables. We can, of course, make different objects such as 'Car1' and 'Car2' interact with
each other. We have now a world of cars. We have been able to successfully build a virtual
world. That is what object oriented programming is all about- simulating the real world
using objects built from classes.
There are three principles of object oriented programming- abstraction, inheritance and
polymorphism. We shall look at them one by one.
Abstraction is the process of representing the essential features of a system without getting
involved with the its complexities. Consider the Car example again. Once you write the 'Car'
class, other people will be able to create Car objects and use them. You need not disclose to
them how you implemented the starting and stopping of the Car. All that you need to tell
them is how those methods can be called. This is what abstraction is all about. Other people
2
are capable of using your Car class, create Car objects, and call methods such as startCar()
and stopCar(). They are capable of starting and stopping the car without knowing how it is
being done. Complexities have been hidden. Only the essentialities have been exposed.
The next feature is inheritance. It is the capability of a new class to inherit the variables and
methods of other classes. The new class can define its own variable and methods in
addition to what have been inherited to provide additional capabilities to the new class. It
is similar to how sons and daughters inherit property and can add their own earned
property to the inherited property. If we talk in terms of the Car example, a new class called
SuperCar can be made to inherit from the class Car so that it will have the functionality of
starting, stopping and changing speed and in addition will be able to perform some special
tasks like flying in the air similar to what we see in Hollywood movies.
Hoping that you understood what object oriented programming is, we now move on to the
details of how classes are defined in Java. For the rest of our discussion about building
classes, we will focus on building different classes.
Object
3
an object would be a person. Logically, you would expect a person to have a name. This
would be considered a property of the person. You could also expect a person to be able to
do something, such as walking or driving. This would be considered a method of the
person.
Code in object-oriented programming is organized around objects. Once you have your
objects, they can interact with each other to make something happen. Let's say you want to
have a program where a person gets into a car and drives it from A to B. You would start by
describing the objects, such as a person and car. That includes methods: a person knows
how to drive a car, and a car knows what it is like to be driven. Once you have your objects,
you bring them together so the person can get into the car and drive.
Syntax:
ClassName ReferenceVariable1 = new ClassName();
An object is a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of:
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
4
other's data or code. The only necessary thing is the type of message accepted and the type
of response returned by the objects.
Example of an object : dog à A dog is an object because it has states like color, name,
breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.
Class
A class is a blueprint of an object. You can think of a class as a concept, and the object is the
embodiment of that concept. You need to have a class before you can create an object. So,
let's say you want to use a person in your program. You want to be able to describe the
person and have the person do something. A class called 'person' would provide a blueprint
for what a person looks like and what a person can do. To actually use a person in your
program, you need to create an object. You use the person class to create an object of the
type 'person.' Now you can describe this person and have it do something.
Classes are very useful in programming. Consider the example of where you don't want to
use just one person but 100 people. Rather than describing each one in detail from scratch,
you can use the same person class to create 100 objects of the type 'person.' You still have
to give each one a name and other properties, but the basic structure of what a person
looks like is the same.
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
5
A class is an entity that determines how an object will behave and what the object will
contain. In other words, it is a blueprint or a set of instruction to build a specific type of
object.
Syntax:
Class <class name> {
field; //variable
method; //function
}
A class as already stated has three major components- variables, constructors and
methods. A class may have all of these, some of these or none. We can create an empty class
which doesn't have variables, constructors or methods but however there would be no use
of such a class. First, we shall look at the outer wrapping of the class which simply names
the class.
Access specifiers that are permitted to be specified for a class are public and private. We
may also leave it unspecified. We can simply write the word class and give a name to it.
Access specifiers are used to define the domain in which an element is accessible. When we
define a class a public, it means that the class is accessible from anywhere. On the other
hand, defining a class as private restricts the accessibility to that particular program file.
We shall look at specifiers again shortly. The word class is a keyword and finally the class
name needs to follow the rules of identifiers. The braces serve the purpose of delimiting the
class. Anything that appears within the braces is a part of the class. A group of statements
enclosed in braces is known as a block.
For now, we will move on to the Student class. We define the Student class in the following
way.
public class Student {
// variables
// constructors
// methods
}
6
At this point of time, it is necessary to understand that we do not have a main method here.
We are of course free to include a main method but we shall test this Student class outside
in a new class (or to be more clear- a program) having a main method.
Now, we shall look at declaring the variables. Variables are declared by specifying the data
type and the variable name. We may optionally state the access specifier also. Variables
declared within the class are accessible to all the methods of the class. These variables
characterize the object that would be instantiated from these classes. Following is the
syntax for variable declaration.
< access specifier > < data type > < variable name >;
We may also give a value to it, which would be the default for objects instantiated from this
class. But, we shall do it in a better way using constructors.
< access specifier > < data type > < variable name > = < value >;
For now, here is the class Student with five variables.
We have applied the private access specifier to each of the variables. When we do so, these
variables are accessible from within the class only. Any attempts to access them from
outside the class will result in compilation errors. This can be better explained when we
bring objects into the scene. We create Student objects from this class. After doing so, we
cannot directly request access to these variables by using the object name and dot operator
in the following way.
7
marks1 variable of a Student object, student1. This isn't allowed since the marks1 variable
was declared to be a private variable. If the variable was public, such a statement would
have been valid. We shall see later on how we can create the object student1. We shall also
see how these variables can be accessed or modified using get and set methods.
// Class Declaration
class Dog
{
// Instance Variables
String breed;
String size;
int age;
String color;
// method 1
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color);
}
}
public class Execute{
public static void main(String[] args) {
Dog alpha = new Dog();
alpha.breed="Alpha";
alpha.size="Small";
alpha.age=2;
alpha.color="white";
System.out.println(alpha.getInfo());
}
}
Output: à Breed is: Alpha Size is: Small Age is:2 color is: white
There are two types of variables in Java, primitive and reference type. All the basic types
e.g. int, boolean, char, short, float, long and double are known as primitive types. JVM treats
8
them differently than reference types, which is used to point objects e.g. String, Thread, File
and others. Reference variables are not pointers but a handle to the object which is created
in heap memory.
The main difference between primitive and reference type is that primitive type always has
a value, it can never be null but reference type can be null, which denotes the absence of
value. So if you create a primitive variable of type int and forget to initialize it then it’s
value would be 0, the default value of integral type in Java, but a reference variable by
default has a null value, which means no reference is assigned to it.
In short, the main difference between two types is that primitive types store actual values
but reference type stores handle to object in the heap.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types, and both
terms will be used in this chapter. These can be put in four groups:
• Integers: This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
• Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
• Characters: This group includes char, which represents symbols in a character set,
like letters and numbers.
9
• Boolean: This group includes boolean, which is a special type for representing
true/false values.
The only way you can access an object is through a reference variable. A reference
variable is declared to be of a specific type and that type can never be changed. Reference
variables can be declared as static variables, instance variables, method parameters, or
local variables.
A reference variable that is declared as final can’t never be reassigned to refer to a different
object. The data within the object can be modified, but the reference variable cannot be
changed.
Reference variables are used to refer to an object. They are declared with a specific type
which cannot be changed. Some common types of reference variables are static variable,
instance variable, method parameter and local variable.
2.3. CONSTRUCTORS
public Student ( ) {
name = null;
rollNumber = -1;
10
marks1 = -1;
marks2=-1;
marks3=-1;
}
The header of a default constructor (the first line) consist of the access specifier and the
constructor name. The constructor's name should be the same as that of the class, which in
this case is 'Student'. Since this is a default constructor that doesn't take any arguments, the
parentheses are left empty. And then, as usual we start a block using an opening curly
brace. We then initialize the variables to some default values. We have initialized the name
to null. A reference data type when initialized to null indicates that the variable doesn't
refer to any object in memory. Recall that String is a reference data type (since it is class).
And we have initialized the remaining integers to -1 to simply indicate that the Student
wasn't initialized with a proper value. You may, if you wish to do so, provide some other
default values. The following default constructor would also be equally fine. But we have
used the null and -1 default values as they reflect the scenario in a biter way.
public Student ( ) {
name = "No name";
rollNumber = 0;
marks1 = 2;
marks2=3;
marks3=10;
}
But, remember that a class cannot have more than one default constructor.
11
marks3= m3;
}
Since this is a parameterized constructor which receives arguments, the required values
have been stated in the parentheses. We state the data type of the required argument and
give a variable name. This particular parameterized constructor was specified with five
parameters. Each of the parameters should be separated by a comma. The body of the
constructor assigns the values received to the instance variables. Suppose we pass the
values "Ethiopia", 34,97,99,98 to this constructor; then "Ethiopia" would be stored in n, 34
in rn, 97 in m1 and so on. And then because of the statement name =n; name will be
initialized with "Ethiopia". In a similar manner, the other variables are also initialized with
the values passed to the constructor. We shall see later on how we pass values to a
constructor while creating an object using the new keyword.
We may define more than one constructor for a class. Suppose, we want to provide the
facility where we should be able to create Student object by simply passing the name and
roll number, and assign the marks to 0, we may do it with the help of another constructor
as shown below.
The process of providing more than one constructor to a class is known as constructor
overloading. However, there are certain restrictions here which we shall see later on when
dealing with constructor overloading. For now, we have declared the variables and
provided three constructors. Now, let us provide a method which will print the details of a
Student. A method definition would be similar to what we have already seen in our
previous programs. The only difference would be that we will now omit the word static and
also remove the String[] args parameter. Static was used earlier since there was a need for
that main method to be called without crated an object of that class, be it HelloWorld or
12
Addition class. The parameter String[] args too had a significance there about which we
shall later on when dealing with command line arguments. String[] is a data type just like
String and int and args was a variable name for the argument that would be passed to main.
We will deal with them later on. For now, here is a method printDetails() which prints the
details of the Student.
This method looks just like a constructor. The difference is that we have a return type and
the name of the method need not be the same as that of the class. The return type here is
void which means that the method will not return any value after execution. We shall see
how to implement methods that return values in a few moments and how to use those
returned values.
We have just started with the design of our Student class but it is still not completed. We
haven't provided a means to modify the values of the variables and there are no methods
that print the total marks and average. However, this current version of the Student class is
sufficient to build objects. Here is the first version of our Student class which has five
instance variables; two constructors- one default and two parameterized and lastly a
method to print details about the student.
The default constructor has been slightly modified to give default value for name as "No
name" instead of null.
public Student ( ) {
13
name = "No name";
rollNumber = -1;
marks1 = -1;
marks2=-1;
marks3=-1;
}
public Student ( String n, int rn, int m1, int m2, int m3) {
name = n;
rollNumber = rn;
marks1 = m1;
marks2 =m2;
marks3= m3;
}
14
2. Explain the difference between default constructors and parameterized
constructors using a program?
_________________________________________________________________________________________________
________________________________________________________________________________________________
Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables. Thus, the
data for one object is separate and unique from the data for another. An instance variable
can be declared public or private or default (no modifier). When we do not want our
variable’s value to be changed out-side our class we should declare them private. public
variables can be accessed and changed from outside of the class.
15
A method is a program module that contains a series of statements that carry out a task. To
execute a method, you invoke or call it from another method; the calling method makes a
method call, which invokes the called method. Any class can contain an unlimited number
of methods, and each method can be called an unlimited number of times. The syntax to
declare method is given below.
Access Modifiers
We have quite often been using the access specifiers- public and private. We shall now see
what these access specifiers actually are, to what entities they can be applied and what
access restrictions are imposed by their usage.
Access specifiers are used to control the visibility of members like classes, variables and
methods. There are three access specifiers: public, private and protected. We shall see only
about the public and private access specifiers for now. Protected access specifier comes
into picture when inheritance is implemented. Also, we may leave the access specifier
keyword unspecified just as we had seen when learning about classes in the beginning. For
example, the following class declaration is also valid though no access pacifier is stated.
class Student {
}
In such cases, the default restrictions (also known as the package restrictions) are applied.
16
Now, we will see what effect these specifiers have on classes, methods and variables.
Before moving further, there is another thing to be noted. A simple program file can contain
more than one class but only one of them should be declared as public. If more than one
class is declared in the same program file, both of them will be considered as different
classes. Or in other words, one class is not said to be contained within the other class. This
is important to be noted to avoid any erroneous interpretation of the restrictions imposed
by access specifiers.
17
Student s = new Student ();
s.name = "Sai"; // allowed
}
}
In the above program, we were able to modify the name variable directly even though the
access specifier was private. This is because the variable was accessed from the same class
itself. If we create an object of the Student class in a new class, such an StudentTest, access
would be denied.
18
}
public static void main ( String[] args ) {
Student s = new Student (); // allowed
}
}
Following table shows what access specifiers may be assigned to different elements. Note
that all four levels may be applied to all elements except classes. Classes may be declared
with only public and private access specifiers
The following table summarizes the above said points regarding the accessibility of
entities. We haven't looked into what a subclass is and the accessibility in a subclass. We
shall see about it when we deal with inheritance.
19
Check your progress-4
1. List and explain the basic access modifiers?
____________________________________________________________________________________________________
____________________________________________________________________________________________________
______________________________________________
this is a keyword in Java. this keyword in java can be used inside the method or constructor
of Class. It(this) works as a reference to the current Object, whose Method or constructor is
being invoked. This keyword can be used to refer to any member of the current object from
within an instance Method or a constructor.
this keyword can be very useful in the handling of Variable Hiding. We can not create two
instances/local variables with the same name. However, it is legal to create one instance
variable & one local variable or Method parameter with the same name. In this scenario,
the local variable will hide the instance variable this is called Variable Hiding.
Example:
class JBT
{
int variable = 5;
20
obj.method(20);
obj.method();
}
1.4. SUMMARY
21
wheels, number of gears) and behavior (braking, accelerating, slowing down, changing
gears).
Software objects are modeled after real-world objects in that they, too, have state and
behavior. A software object maintains its state in variables and implements its behavior
with methods. Constructors are used to initialize an object. Default constructors do not
accept any parameters while parameterized constructors accept parameters.
The basic access modifiers are: public: Members (variables, methods, and constructors)
declared public (least restrictive) within a public class are visible to any class in the Java
program, whether these classes are in the same package or in another package.
protected: The protected fields or methods, cannot be used for classes and Interfaces.
Fields, methods and constructors declared protected in a super-class can be accessed only
by subclasses in other packages. Classes in the same package can also access protected
fields, methods and constructors as well, even if they are not a subclass of the protected
member’s class. Default (no value): The default access level is declared by not writing any
access modifier at all. Any class, field, method or constructor that has no declared access
modifier is accessible only by classes in the same package. Private: The private (most
restrictive) modifiers can be used for members but cannot be used for classes and
Interfaces. Fields, methods or constructors declared private are strictly controlled, which
means they cannot be accessed by anywhere outside the enclosing class.
I: True/False questions
1. An Object can be defined as an instance of a class.
2. The private modifiers can be used for members but cannot be used for classes
and Interfaces.
3. Encapsulation is the process of representing the essential features of a system
without getting involved with the its complexities.
4. The process of providing more than one constructor to a class is known as
constructor overloading.
5. The only way we can access an object is through a primitive variable.
22
II: Short Answer Questions
1. What is the difference between constructors and methods?
2. Describe the relationship between an object and its defining class. How do you
define a class? How do you declare an object reference variable? How do you create
an object? How do you declare and create an object in one statement?
23