0% found this document useful (0 votes)
7 views

UNIT 2

Unit 2 covers the fundamentals of Object-Oriented Programming (OOP), focusing on classes and objects, reference versus primitive variables, constructors, and access modifiers in Java. It explains key OOP principles such as abstraction, inheritance, and polymorphism, using examples like a 'Car' class to illustrate how objects interact and represent real-world entities. The unit also distinguishes between primitive and reference variables, detailing their characteristics and usage in Java programming.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

UNIT 2

Unit 2 covers the fundamentals of Object-Oriented Programming (OOP), focusing on classes and objects, reference versus primitive variables, constructors, and access modifiers in Java. It explains key OOP principles such as abstraction, inheritance, and polymorphism, using examples like a 'Car' class to illustrate how objects interact and represent real-world entities. The unit also distinguishes between primitive and reference variables, detailing their characteristics and usage in Java programming.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT 2: CLASSES AND OBJECTS

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

2.0. AIMS AND OBJECTIVES

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:

• Understand the concepts of OOP such as objects and classes


• Use the access modifiers in writing programs
• Know the difference between reference variables and primitive variables

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.

The final feature of object oriented programming that is to be discussed is polymorphism.


This is the property by which different objects can react to the same method call or in
simpler terms a message, and still produce the correct output i.e. the desired output. If we
talk in terms of our Car, then we can state the feature of polymorphism as the ability to
change speed to both a numeric value and a fractional value. Different methods in those
classes will handle these calls but still the message that would be passed would be the
same, which is changeSpeed(). The only difference is in the arguments (the information to
be passed). While one call passes 34 as an argument, the other call would pass 34.7 as the
argument. These things might appear trivial for now but you will be able to appreciate
these features later on when we deal with how these features are implemented in Java.

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

Object-oriented programming, or OOP, is an approach to problem solving where all


computations are carried out using objects. An object is a component of a program that
knows how to perform certain actions and how to interact with other elements of the
program. Objects are the basic units of object-oriented programming. A simple example of

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:

1. State: It is represented by attributes of an object. It also reflects the properties of an


object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, “menu”. An online shopping system might have
objects such as “shopping cart”, “customer”, and “product”. Any entity that has state and
behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can
be physical or logical.

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:

1. Modifiers: A class can be public or has default access


2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass (if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body surrounded by braces, {}.

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 specifier> class <class name> {

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.

public class Student {


private int rollNumber;
private String name;
private int marks1;
private int marks2;
private int marks3;
}

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.

student1.marks1 = 100; // student1 is of type Student


Recall that we have used the dot operator several times earlier in the print( ) statement.
The dot operator is used to access members of classes and objects. Earlier we have
accessed the out variable of the class System. While now, we are trying to access the

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.

Objects and Classes example:

// 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

Check your progress-1


1. What are classes and objects in OOP? Explain them with java program?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
2.2.REFERENCE
2.2.REFERENCE VARIABLES AND PRIMITIVE VARIABLES

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.

Check your progress-2


1. List and explain the basic difference of primitive and reference variables?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
__________________________________________________

2.3. CONSTRUCTORS

Now, we move on to constructors. Constructors are used to initialize an object.


Constructors appear somewhat similar in syntax to methods but there are a few
differences. There are two types of constructors- default constructors and parameterized
constructors. Default constructors do not accept any parameters while parameterized
constructors accept parameters. Recall that variables stated within the parentheses are
referred to as parameters. These parameters have a data type and a variable name. We
shall now first look into how we can provide a default constructor.

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.

We now move onto to parameterized constructors. Parameterized constructors accept


arguments which are data items that are used to initialize the variables of a class. Following
shows a parameterized constructor for a class where the five variables are initialized with
arguments that would be received by the constructor.
public Student ( String n, int rn, int m1, int m2, int m3) {
name = n;
rollNumber = rn;
marks1 = m1;
marks2 =m2;

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.

public Student ( String n, int rn) {


name = n;
rollNumber = rn;
marks1=0;
marks2=0;
marks3=0;
}

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.

public void printDetails() {


System.out.println("Roll Number: "+ rollNumber);
System.out.println("Name: "+name);
System.out.println("Marks in first subject: "+marks1);
System.out.println("Marks in second subject: "+marks2);
System.out.println("Marks in second subject: "+marks3);
}

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 class Student {


private int rollNumber;
private String name;
private int marks1;
private int marks2;
private int marks3;

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;
}

public Student ( String n, int rn) {


name = n;
rollNumber = rn;
marks1=0;
marks2=0;
marks3=0;
}

public void printDetails() {


System.out.println("Roll Number: "+ rollNumber);
System.out.println("Name: "+name);
System.out.println("Marks in first subject: "+marks1);
System.out.println("Marks in second subject: "+marks2);
System.out.println("Marks in second subject: "+marks3);
}

Check your progress-3


1. What are constructors?
_________________________________________________________________________________________________
________________________________________________________________________________________________

14
2. Explain the difference between default constructors and parameterized
constructors using a program?
_________________________________________________________________________________________________
________________________________________________________________________________________________

2.4. JAVA DECLARATION


DECLARATION AND ACCESS MODIFIERS

An object-oriented program can be characterized as data controlling access to the code.


Java is object-oriented programming language. Java classes consist of variables and
methods (also known as instance members).
A class is declared by use of the class keyword. The class body is enclosed between curly
braces { and }. The data or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively, the methods and variables defined
within a class are called members of the class.

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.

Access specifiers for classes


When a class is declared as public, it is accessible to other classes defined in the same
package as well as those defined in other packages. This is the most commonly used
specifier for classes. A class cannot be declared as private. If no access specifier is stated,
the default access restrictions will be applied. The class will be accessible to other classes in
the same package but will be inaccessible to classes outside the package. When we say that
a class is inaccessible, it simply means that we cannot create an object of that class or
declare a variable of that class type. The protected access specifier too cannot be applied to
a class.

Access specifiers for instance variables


Accessibility of instance variables can be controlled with all the four access specifiers-
public, private, protected and the default restriction (no access specifier mentioned). When
a variable is declared as public, it can be modified from all classes in the same or different
packages. When we talk of modification here, it refers to the modification of the variables
corresponding to an object built out of this class and not the variable of the class itself. If no
access specifier is stated, then these variables are accessible from classes in the same
package only. If the variable is private, access is restricted to the class itself. If we create an
object of this class in the main method of the same class, the variable is accessible but if the
object is created in different class, the variable is accessible. Look at the following sample
code for example.
public class Student {
private name;
public static void main ( String[] args ) {

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.

public class StudentTest {


public static void main ( String[] args ) {
Student s = new Student ();
s.name = "Sai"; // not allowed
}
}

Access specifier for methods


Access specifiers for methods work in a similar way to that of variables. Methods too can be
defined using all four levels of access protection.

Access specifiers for constructors


All four access restriction may be applied to constructors. When we talk of accessing a
constructor, it refers to creating an object of that class using that particular constructor. If a
constructor is declared as public, its objects can be created from any other class. If no
access specifier is stated, its objects may be created from classes belonging to the same
package only. If the private access specifier is applied, objects may be created in that
particular class only. However, we generally do not apply the private access specifiers to a
constructor if the class contains only a single constructor as this may render the class
unusable. Look at the following code where a constructor is declared as private. We can
create objects within the same class only. In this particular example, we have created the
object in the main method of the class. Attempting to create the object in different class
would result in compilation errors.

public class Student {


public name;
private Student() {

18
}
public static void main ( String[] args ) {
Student s = new Student (); // allowed
}
}

public class StudentTest {

public static void main ( String[] args ) {


Student s = new Student (); // not 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?
____________________________________________________________________________________________________
____________________________________________________________________________________________________
______________________________________________

2.5. THIS KEYWORD


KEYWORD IN JAVA

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;

public static void main (String args[]) {


JBT obj = new JBT();

20
obj.method(20);
obj.method();
}

void method(int variable) {


variable = 10;
System.out.println("Value of Instance variable :" + this.variable);
System.out.println("Value of Local variable :" + variable);
}
void method() {
int variable = 40;
System.out.println("Value of Instance variable :" + this.variable);
System.out.println("Value of Local variable :" + variable);
}
}

The output of the above program

Value of Instance variable :5


Value of Local variable :10
Value of Instance variable :5
Value of Local variable :40

Check your progress-5


1. What is the role of ‘this’ keyword in programming language?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
__________________________________________________

1.4. SUMMARY

As the name object-oriented implies, objects are key to understanding object-oriented


technology. You can look around you now and see many examples of real-world objects:
your dog, your desk, your television set, your bicycle. These real-world objects share two
characteristics: they all have state and they all have behavior. For example, dogs have state
(name, color, breed, hungry) and dogs have behavior (barking, fetching, and slobbering on
your newly cleaned slacks). Bicycles have state (current gear, current pedal cadence, two

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.

1.5. MODEL EXAMINATION QUESTIONS.

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

You might also like