II-I R23 OOPJ Module-2 Lecture Notes
II-I R23 OOPJ Module-2 Lecture Notes
MODULE-2
Syllabus
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of Class
Objects, Assigning One Object to Another, Access Control for Class Members, Accessing Private Members of
Class, Constructor Methods for Class, Overloaded Constructor Methods, Nested Classes, Final Class and
Methods, Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class
Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding
Methods, Attributes Final and Static.
• Nested class: It is a class that is declared within the body of another class or interface.
• Nested static class: It is like any other static member of the enveloping class.
• Nested non-static classes are also called inner classes and it can be classified as follows:
– Member inner class: It has properties like any other member of the outer class.
– Anonymous class: As the name indicates, it is the inner class without a name.
• Derived class or subclass: It is a class that is derived from (or extends) another class.
• Super class: It is a class from which another class or other classes are derived.
• Generic classes: These are classes that declare one or more type parameters.
Note that the declaration starts with the modifier, which is discussed. However, a class may be declared without
a modifier. It is followed by keyword class, which is followed by the name or identifier for the class. The
body of class is enclosed between a pair of braces {}.
The conventions that are generally followed for naming the classes include the following rules:
• The class names should be simple and descriptive.
• Class names should start with an upper-case letter and should be nouns. For example, it could include
names such as vehicles, books, and symbols.
• It should have both upper- and lower-case letters with the first letter capitalized.
• Acronyms and abbreviations should be avoided.
CLASS MODIFIERS
Class modifiers are used to control the access to class and its inheritance characteristics. Java consists of
packages and the packages consist of sub-packages and classes. Packages can also be used to control the
accessibility of a class. These modifiers can be grouped as access modifiers and non-access modifiers.
The modifier private and protected are used only for nested class. A private class is declared inside another
class. Therefore, this class is visible to other members of the enveloping class in which it is declared. For all
other classes, this class is not visible.
Classes with the final modifier are declared as follows. A class with the modifier final cannot be extended,
that is, it cannot have subclasses but it can have a super class. This means that the final class itself can be a
derived class but no class can be derived from it.
An abstract class must have at least one abstract method, that is, a method without a body; it is only the header
of a method followed by a semicolon. An abstract class cannot have its own objects. However, its concrete
subclasses that give complete definitions of the abstract methods can have objects and are implemented. Since
abstract class cannot have objects, it will not have constructor method.
CLASS MEMBERS
The class members are declared in the body of a class. These may comprise fields (variables in a class),
methods, nested classes, and interfaces. The members of a class comprise the members declared in the class
as well as the members inherited from a super class. The scope of all the members extends to the entire class
body.
The fields comprise two types of variables:
1. Non-static variables: These include local and instance variables which vary in scope and value.
a) Instance variables: These variables are individual to an object and an object keeps a copy of these
variables in its memory.
b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables: These variables are also qualified as static variables. The values of these variables are
common to all the objects of the class. The class keeps only one copy of these variables and all the
objects share the same copy. As class variables belong to the whole class, these are also called class
variables.
Instance variables across different objects have different values, whereas class variables across different
objects have only one value. Class variables are initialized when a class is first loaded into JVM memory,
whereas instance variables are initialized when an instance is created.
In the aforementioned program, line 1 defines class CustomerId. In line 3, static variable count is initialized
to zero. As can be seen, the static variable count is initialized when the class is first loaded in JVM memory.
In line 16, an instance of the class CustomerId is created and it accesses the id of the customer.
The object comes into existence only when a physical copy of object of class (i.e., the required memory and
instance variables) is assigned to it by the operator new. The new operator creates a new object or an
instance of a class. With this, the object is created. In practice, this dynamically allocates memory in the
heap at run time of the program.
For example, let us have a class defined as
This statement creates a physical object in the heap with the reference variable ‘myFarm’ pointing to the object
from the stack. Here, myFarm is a variable of the type Farm. Each object of the Farm class has allocated
memory that can hold the values of instance variables length and width. Figure illustrates the states of object
after declaration and after definition or allocation of memory.
In the aforementioned definition, Farm is the type and myFarm is the name of the object. The operator new
allocates the necessary memory space for holding the two int variables—length and width. Figure gives a
physical picture of myFarm.
ASSIGNING ONE OBJECT TO ANOTHER
When one object of a class provides a reference to another object of the same class, the first object can access
the second object’s data and methods.
To understand this concept better, let us begin the discussion with an example program.
If you see the results of Program carefully, it becomes clear that object names farm1 and farm2 are only
references to the objects. When we assign farm1 to farm2, we are in fact only assigning the reference, that is,
farm2 becomes another reference to the same object represented by farm1. The farm2 is not an independent
new object. The following assignment only creates another reference to the same object.
This has already been explained by the output of Program. The assignment is illustrated in Fig. The instance
variables may be accessed through a member method of the class.
ACCESS CONTROL FOR CLASS MEMBERS
The access to a class member can be controlled by placing an appropriate access specifier in the class
definition. Three access specifiers are permitted as follows:
• public
• protected
• private
The coding with access specifiers for variables is illustrated as
Further, there may not be any access specifier, and therefore, this gives another option of access; in general,
four types of access conditions are there. The access attribute may be placed in class definition in any order.
See the following examples.
The class also defines another method area() to which the values are passed for calculation of area when the
method area() is invoked by the object. For obtaining values of length and width by outside code, two public
methods are defined as
These methods may be invoked by objects of the class to obtain the values of variables as follows:
Explanation
The program defines three classes: (a) with name Outer declared in lines 1–22, (b) the non-static nested class
with name Inner declared in lines 14–21, and (c) class Nest with main method declared in lines 23–30 and
executes the class Outer. In the class Nest, an object with name obj of outer class is defined in line 26. It calls
the method displayOuter() defined in lines 10–13. The displayOuter contains a statement that defines an object
of class Inner with name iner and a statement in which the object iner calls the displayInner() method of inner
class. The output is given. In Program, the inner class is declared as a private class. Since it is a member of
the class Outer, the other members of outer class have access to the private class. The method displayOuter()
of outer class has statements that define the inner class object as well as a call for inner class method
displayInner(). The code is given.
Therefore, when the method displayOuter is called, it automatically calls the displayInner() method through
the object of inner class.
ANONYMOUS CLASS
As the name indicates, anonymous classes are inner classes without a name. It is defined inside another class.
Because class has no name it cannot have a constructor method and its objects cannot be declared outside the
class. Therefore, an anonymous class must be defined and initialized in a single expression. An anonymous
class may be used where the class has to be used only once. An anonymous class extends a super class or
implements an interface, but keywords extend or implements do not appear in its definition. On the other hand,
the names of super class and interface do appear. An anonymous class is defined by operator new followed by
class name it extends, argument list for the constructor of super class, and then, the anonymous class body.
For implementation of an interface, the anonymous class is defined by the operator new followed by interface
name it extends, empty pair of parentheses, and the class body.
Explanation: In this program, an anonymous class extends an abstract class. An abstract class by name Person
is declared in lines 1 to 3. Line 4 declares a class AnonymousDemo2 and its main method is declared in line
5. Lines 7–9 define an expression containing an anonymous class. In line 7, the main method declares an
instance of class person and defines the method display, which is implemented in line 11. The output is shown.
Program illustrates an anonymous class that implements an interface.
LOCAL CLASS
A local class is declared in a block or a method, and hence, their scope is limited to the block or method. The
general properties of such classes are as follows:
• These classes can refer to local variables or parameters, which are declared final.
• These are not visible outside the block in which they are declared, and hence, the access modifiers
such as public, private, or protected do not apply to local classes.
Explanation
A local class is a class declared in a block or method. In the aforementioned program, it is declared in main
method in code lines 4–9 by name Local. This class defines a private instance variable int x. Line 6 is the
constructor of the class Local, which also defines a method display(). An object of class Local by name local
is declared in line 10 and it invokes the method display of Local class. The result is shown in the output.
STATIC NESTED CLASS
It is a member of enveloping class like any other static member. Its general properties are as follows.
• It may be declared public, private, or protected. However, these classes cannot access the non-static
instance variables and methods. They can access only static instance variables and methods.
• The main benefit of these classes is that their reference is not attached to outer class reference.
Their object may be accessed directly. For the access, the fully qualified name is not needed.
• An instance of outer class is not needed for declaring the instance of nested static class outside the
outer class.
• The nested static class may be accessed inside the main method without the reference of outer class.
• The class may be imported to a program by static import.
• It may simply be referred to by its class name.
Explanation
By declaring the inner class static, we can declare its object outside the scope of outer class by using outer
class name and can call the method of inner class directly by its object. Object of outer class Obj is also
defined in the program and method area is called through it.
Code lines 1–18 define the class Outer1 in which a static inner class is defined in lines 9–17. Object inn1 of
class Inner2 is created with name of outer class Outer1 in line 23 and this object invokes the method
displayInner() of inner class.
FINAL CLASS AND METHODS
It is possible that we can declare the entire class as final. A class that is declared final cannot have a subclass.
This becomes important in order to prevent hackers from accessing and changing private information. In
order to specify the class as final, keyword final is used before the class keyword in class declaration. If we
just want to protect some of our class’s methods from being overridden, declaring the whole class as final
is not required; We can declare some or all of the class’s methods as final. For this, final keyword in method
declaration is used.
Explanation
In line 1, final class is declared. Method displayA() is defined in line 3, which is also a final method and
cannot be overridden. In line 7, class B1 extends class A1. Since class A1 is final, it cannot be extended due
to which an error message is obtained in the output.
ABSTRACT CLASS
Abstract classes are those classes having one or more abstract methods. The basic idea behind an abstract
class is to provide a generic concept instead of a specific class that performs some specific function. An
abstract method provides declaration only and does not contain any implementation. Further, an abstract
class cannot be used to instantiate objects directly with the new operator. To provide the implementation
of abstract methods, subclasses of abstract class are created that can be instantiated. For creating an abstract
class, abstract keyword is used before the class keyword in the class declaration.
Explanation: Line 1 declares an abstract class and abstract method is declared in line 2. A subclass Square is
declared in line 4 that defines the method draw(). Similarly, another subclass is declared in line 9, which also
defines the method. In lines 14–22, class containing the main method is defined. Objects of class Square and
Triangle are created in lines 16 and 17.
Explanation:
In this program, the method func() receives the value of n as value of an instance variable of an object of class
Ref (code lines 1–8). Therefore, every time the method is called, the current value of n with the object is
passed to the method that increases the value by 4. For refObj1, the starting value of n = 10. On the first call
of the func(), the value of n increases to 14 and on the second call, it goes to 18. Similarly, the changes in
values of refObj2 may be explained. The start value is 20; on the first call of func(), it increases to 24, and on
the second call, it goes to 28.
KEYWORD this
INSTANCE VARIABLE HIDING
There may be cases where the names of instance variables and that of the local variable in a method is the
same. In such cases, the local variables of the method shadow the instance variable, thereby hiding them.
Program illustrates this case.
Explanation:
Line 1 declares the class Demo. Instance variable is defined in line 3. Object of class Demo is instantiated in
line 5. Methods declared in lines 7–8 are defined in lines 11–14 and in lines 17–20, respectively. In line 12,
local variable is assigned a value of 20, and hence, the output is displayed as 20. Likewise in line 18, the output
is displayed as 40.
The value of instance variable having the same name as local variable has been shadowed or hidden. In order
to overcome this problem of instance variable hiding, this keyword is used. The keyword this provides
reference to the current object. An application of this is illustrated in Program
METHODS
A method in Java represents an action on data or behaviour of an object. In a program, the raw material is
the data and the process is the method that consists of several statements; these statements process the data
in many different ways.
In fact, there are infinite different ways in which the two aspects (action and behaviour) of methods are
manifested. A few types of actions and behaviour commonly used in programming are listed here.
1. It could involve carrying out computation on data presented to method.
2. The action may simply be rearranging the elements of an object, for example, sorting arrays.
3. The action may comprise finding or searching for the object for some purpose, such as searching for a
value in arrays or a collection of objects or a site on the Internet.
4. A method may comprise a selection of specific objects from the list presented to it.
5. The action may simply be the initialization of an object.
6. Methods may create images, voice, and multimedia as well as display.
7. Methods may define how an object will communicate with other objects or with users of programs.
8. It may simply answer an enquiry.
9. A method may tell whether an action is permissible or not.
A method is an encapsulation of declarations and executable statements meant to execute desired
operations.
DEFINING METHODS
A method definition comprises two components:
• Header that includes modifier, type, identifier, or name of method and a list of parameters. The
parameter list is placed in a pair of parentheses.
• Body that is placed in braces ({}) and consists of declarations and executable statement and other
expressions.
A method may or may not throw an exceptional condition. A definition of method that does not throw an
exception is illustrated in the following statements.
The arguments passed on at the time of calling the method have to be placed in the same order and type as in
the definition; otherwise, the compiler may send an error message if there is a mismatch or the program may
give the wrong result.
RETURN STATEMENT
In the case of methods of type void no return statement is required. The program control automatically returns
to the calling method after the end of method, that is, after the closing brace (}). However, in return type
methods, the last statement is the return statement, that is, return value. The following examples illustrate the
return statement.
In the case of void methods, the returned statement is optional. It may not be included in the method. However,
for any other type of method, the return statement is mandatory.
The compute is of type int, and therefore, the last statement is the return statement.
OVERLOADED METHODS
Methods with the same name and scope are permitted provided they have different signatures that include the
following:
• Number of parameters
• Types of parameters
• Their order in the parameter list
Any one or more of the aforementioned factors should be different. The compiler executes the version of the
method whose parameters match with the arguments. For example, the following types of declarations in the
same scope are permissible.
Explanation: Constructor method can also be overloaded like any other method. The program declares four
constructors, that is, parametric constructor, copy constructor, constructor with one parameter and default
constructor. The class objects are declared with different parameters and the compiler chooses the appropriate
constructor method to construct them. In the case of object farm1, two arguments are given, and therefore,
parametric constructor is selected for it. For farm2, the copy constructor is chosen. For farm3, no arguments
are provided, and therefore, the default constructor is selected for it. Similarly, for farm4 with one argument,
the one parameter constructor is chosen. In the selection of constructor, the arguments provided with object
are matched with parameters of the method.
CLASS OBJECTS AS PARAMETERS IN METHODS
Similar to any other primitive parameter, an object of a class may also be a parameter of a method. The type
of an object of a class is the name of its class. The operations that the class object may be subjected to are the
ones derived from the class Object and those defined in its own class and the super class if it is the object of a
derived class.
Explanation: The program defines the equality condition of two farms based on area. The farms are equal if
their areas are equal. The method equals () defined takes the object of class as parameter. The class is executed
by another class with main method declared. The area of farm3 is same as the area of farm2. Therefore, we
get the result true. The areas of farm3 and farm1 are not equal, and therefore, we get the output false.
ACCESS CONTROL
Java supports access control at the class level and at the level of class members. At the class level, the following
two categories are generally used:
1. Default case—no modifier applied
2. public
A class declared public may be accessed by any other class in any package. In the default case, when no access
specifier is applied, the class can be accessed by other classes only in the same package. In a class, Java
supports the information hiding mechanism so that the user of a class does not get to know how the process is
taking place. We can only operate with the methods meant for them to use. A class contains data members and
method members or a nested class. The access to any of the members—data, method, or nested class—can be
controlled by the following modifiers.
1. private
2. protected
3. public
4. default case—no modifier specified
ACCESSING PRIVATE DATA MEMBERS
The private members can only be accessed by the other members (methods) of the same class. No other code
outside the class can access them. If it is desired to get the values of private data by outside code, it can only
be done through public methods that are defined in the class for this purpose. For instance, we can use methods
such as getx (), as illustrated in the following code.
Explanation: The program declares two private instance variable members, that is, length and width in lines
2 and 3. For accessing these variables, we declare a public method void setValue(). Further, to get these
dimensions, two more public methods getLength() and getWidth() are defined in lines 9 and 10. The class
Exec5 declared in lines 13–25 with main method declares two objects f1 and f2 of class Farm.
ACCESSING PRIVATE METHODS
To get the result of a private method, we have to declare a public method in the same class that simply passes
on the result of a private method. An illustration is given by the following code.
getArea() is a public method that simply passes on the value returned by the private method.
RECURSIVE METHODS
It is a technique of defining a method so that it calls itself in one of its statements. In some cases, the problem
itself provides this opportunity, as explained here. The factorial of a number is given as
Therefore, in the definition, the function is called again and again until the multiplying factor is equal to 1. If
it is programmed as in the aforementioned example, it would be called a recursive method.
NESTING OF METHODS
It implies a method calling another method in the same class. Since a method calls another method in the same
class, dot(.) operator is not needed when it is called. The following possibilities are allowed:
1. A method can call more than one method in the same class.
2. Successive calls can be made. This implies the first method calls the second method; the second method
calls the third method, and so on.
Explanation:
In the aforementioned program, since the input is to be entered by the user, we would need the Scanner class.
For this, import statement for importing Scanner class is included in line 1. Line 2 declares the class Rectangle.
In line 3, the method perimeter() is defined. In line 6, another method area() is defined. Within this method,
the method perimeter is nested. Line 12 declares the main method. In line 13 new object of Scanner class is
declared with the argument ([Link]). When the program is run, it prompts the user to enter the length and
breadth of the rectangle in lines 14 and 16, respectively. These values are assigned to l and b respectively. Line
18 defines an object of class which calls the method area (l,b).
OVERRIDING METHODS
A method defined in super class can be inherited by its subclass. This feature of inheritance allows us to define
and use the same methods as in the super class. Inheritance allows deriving new classes from the old one and
reusing the properties of the existing one. In some cases, it may be required that objects in a subclass use the
same method that is defined in the super class, but with different behaviour. Then, in that case, the method is
said to be overridden. The method defined in subclass will be executed and it will hide the definition given in
the super class. The super class definition is executed only if it is qualified by attribute super and a period.
It is different from overloading of methods, in which case, several methods have the same name but the
parameter list has to be different in type or number, or order of parameters. In the case of overloaded methods,
the parameter lists are matched with the arguments to choose the appropriate method that may be in the super
class or subclass. However, in the case of overriding methods, the type signatures of methods defined in the
super and in subclass have to exactly be the same.
ATTRIBUTES FINAL AND STATIC
FINAL
The modifier final may be used with variables as well as with methods and classes. If a variable is declared
final, it makes it a constant. Its value cannot be changed in a program. The value is assigned right in the
beginning. In Program, an example of a final variable is taken.
Explanation:
In line 3, final variable is assigned some value. The value of this variable is then changed in line 6. Since a
variable is declared as final, its value cannot be changed. Therefore, the compilation error is obtained.
A method can also be made as final. In that case, it would mean that the method cannot be overridden in the
subclasses, that is, the definition of the method cannot be changed. This is exemplified in Program.
Explanation: In line 2, final method is defined inside the class Motor. In line 6, class AcMotor extends the
class Motor. In this subclass, the same method, as defined in its base class, is used; however, it has been
modified by changing its arguments. If a method is defined as final, it can be inherited but cannot be
overridden; therefore, in the output, compilation error has occurred. If a class is declared final, the class cannot
have any subclass, that is, its inheritance is prevented.
STATIC METHODS
By declaring a method static, it becomes a class method. Then, it is not necessary that it should be called
through an object. Static methods belong to the class, and therefore, it can be accessed without declaring an
object of the class. If any variable is preceded with the keyword static, it becomes a static variable. For
instance,
Static methods can only access static variables directly. It cannot directly access non-static variables. If a
variable is declared as static, it means that it always resides in the same memory location. To make methods
static, we precede the method declaration with keyword static. The main method is also a static method and
this implies that in order to access instance variables and methods, we need to create objects of the class within
the main method.
END OF MODULE-2