Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Students frequently turn to Computer Class 12 GSEB Solutions and GSEB Computer Textbook Solutions Class 12 Chapter 8 Classes and Objects in Java for practice and self-assessment.

GSEB Computer Textbook Solutions Class 12 Chapter 8 Classes and Objects in Java

Question 1.
What do you mean by instantiation of an object ?
Answer:

  • Creating objects : Creating an object from a class requires the following steps :
    1. Declaration : A variable (reference variable) name of type class is declared with syntax.
      <class name> <variable name>
    2. Instantiation : Keyword new is used to create the object by allocating memory.
    3. Initialization : Constructor (a special type of method) is called to initialize the newly created object.
  • In Java, a class is a type, similar to the built-in types such as int and Boolean. So, a class name can be used to specify the type of a variable in a declaration statement, the type of a formal parameter or the return type of a function.
  • To declare an object of class ‘Room’, use following statement: Room rl;
  • Declaring a variable does not create an object. This is an important point to be remembered. In Java, no variable can ever store an object. A variable declared using class type can only store a reference to an object. So variables of class type are also referred to as reference variables. Here rl is a reference variable.
  • Next step is to create an object. Using new keyword, an object can be created. Operator new allocates the memory for an object and returns the address of the object for later use. Reference is the address of the memory location where the object is stored. In fact, there is a special portion of memory called the heap where the objects live.
  • When an object is created, in addition to allocating memory, a special method called ‘constructor’ is executed to perform initial task.
  • An object can be created of type Room and assign its address to variable rl as follows :
    rl = new Room();
  • Here, parentheses are important. With empty parentheses without arguments, a default constructor is called. It initializes the attributes (variables) of the object using default values.
  • The parentheses can contain arguments that determine the initial values of variables. This is possible by using user-defined constructor.
  • When statement “rl=new Room();” is executed, that object is not stored in variable rl. Variable rl contains only address of an object.
  • Both the above steps used to declare and create an object can be combined into a single statement as follows :
    Room r2 = new Room();
  • Variable r2 contains a reference or address of memory location where a new object is created.
  • It is also to be noted that the class determines only the types of the variables. The actual data is contained inside the individual objects and not in the class. Thus, every object has its own set of data.
  • In code listing two objects rl and r2 have ‘been created using new operator.
  • These objects are allocated different memory space to hold their data values as seen in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 1

  • In Java, when objects are no more needed, the memory is claimed back for reuse.
  • Java has a garbage collector that looks for unused objects and reclaims the memory that those objects are using.
  • There is no requirement to do any explicit freeing of memory.
  • In Object-oriented programming (OOP) languages, creating an object is also called object instantiation.
  • An instance for an object is created by allocating memory to store data for that object.
  • An object that belongs to a class is said to be an instance of that class.
  • Thus, an instance of a class is another word for an actual object. Class is an abstract representation of an object, whereas an instance is its concrete representation.
  • The terms instance and object are often used interchangeably in OOP language.
  • Each instance of a class can hold different values for its attributes in variables declared in a class.
  • Such variables are referred to as instance variables.
  • Instance variables are created at the time of creating an object and stay throughout the life of the object.
  • Instance variables define the attributes of an object.
  • The class defines the kind of attribute. Each instance stores its own value for that attribute.
  • To define an object’s behaviour, methods are created.
  • In Java, methods can be defined inside a class only.
  • These methods can be invoked using the objects to access or modify the instance variables.
  • Such methods are known as instance methods.
  • Instance methods are used to define behaviour of an object.
  • Invoking a method is to ask the object to perform some task.
  • In code listing, a class named Room is defined with instance variables length, width, height and nWindows and instance methods setAttr(), display!) and area().
  • To summarize :
    • Objects are created with the new keyword.
    • The new keyword returns a reference to an object that represents an instance of the class.
    • All instances of class are allocated memory in data structure called heap.
    • Each object instance has its own set of data.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Question 2.
Give an example for the need of class variable.
Answer:
Class Variables and Class Methods

  • When an object is created using new keyword, memory is allocated from heap area to store the value of its attributes.
  • Thus every object has its own instance variables occupying different space in memory.
  • Now, suppose the requirement of the programmer is to have a total number of windows of all Room objects created so far.
  • To store this value, it requires only one variable per
  • It is meaningless to keep this variable as an attribute of each object.
  • Thus, when there is a need to have some variable that is shared by all object instances of the same class, the variable should be allocated the memory only once per class.
  • It means that variable belongs to a class and not to an object.
  • Such variables can be declared within a class using static keyword before data type and these static variables are called class variables.
  • Values of instance variables are stored in instance (memory allocated for the object); whereas values of class variables are stored in class itself.
  • Let us declare class variable totWindows by adding following statement in class with instance variables :
    static int totWindows;
  • Static variables can be accessed without creating an instance of a class.
  • For example, if the programmer tries to display the value of totWindows without creating any object of a class ‘Room’, it will display 0.
  • Just like class variable, class method can be defined using static keyword in front of the method definition.
  • Try following method in ‘Room’ class to display total windows.
static void displayTotalWindows()
{
System.out.println("Total Windows: " + totWindows);
}
  • Class variables and class methods can be accessed outside the class using
    <classname> <class variable / method name>
  • For example : Room.totWindows,
    Room.displayTotalWindows ()
  • Note that class members (variables and methods) can be referred without class name by the methods of the same class as shown in code listing of figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 2

  • The output of the code shown in figure is given in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 3

  • Here, an additional instance method setWindowsO has been written, that updates total windows by subtracting the old number of windows and adding new number of windows in a room.
  • Method setWindows is defined in the same class. So it can access class variable totWindows without class name. In main() method (defined in RoomDemoStatic class) that is defined outside ’Room’ class, class variable totWindows is to be accessed as Room.totWindows using class name.
  • Class methods are global to the class itself and available to any other classes or objects.
  • Therefore, class methods can be used anywhere regardless of whether an instance of the class exists or not.
  • The methods that operate on a particular object, or affect that object, should be defined as instance methods. Methods that provide some general utility but do not directly affect an instance of the class are better declared as class methods.
  • For example, consider a function that determines whether a given number is prime or not.
  • This function should be defined as class method.
  • The code listing and its output is shown in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 4

  • The designers of Java have already provided a large number of built-in classes with such class methods.
  • The static and the non-static portions of a class serve different purposes.
  • The static definitions in the source code specify the things that are part of the class itself; whereas the non-static definitions in the source code specify the things that will become part of every instance object belonging to a class.

Points to Remember :

  • Class variables and class methods can be accessed using a class name or reference variable. To increase readability, it is advised to access with class name.
  • Class variables and class methods can be accessed from instance methods also.
  • Instance variables and instance methods can’t be accessed from class methods, as class methods do not belong to any object.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Question 3.
Write the differences between methods and constructors.
Answer:
Class Variables and Class Methods

  • When an object is created using new keyword, memory is allocated from heap area to store the value of its attributes.
  • Thus every object has its own instance variables occupying different space in memory.
  • Now, suppose the requirement of the programmer is to have a total number of windows of all Room objects created so far.
  • To store this value, it requires only one variable per
  • It is meaningless to keep this variable as an attribute of each object.
  • Thus, when there is a need to have some variable that is shared by all object instances of the same class, the variable should be allocated the memory only once per class.
  • It means that variable belongs to a class and not to an object.
  • Such variables can be declared within a class using static keyword before data type and these static variables are called class variables.
  • Values of instance variables are stored in instance (memory allocated for the object); whereas values of class variables are stored in class itself.
  • Let us declare class variable totWindows by adding following statement in class with instance variables :
    static int totWindows;
  • Static variables can be accessed without creating an instance of a class.
  • For example, if the programmer tries to display the value of totWindows without creating any object of a class ‘Room’, it will display 0.
  • Just like class variable, class method can be defined using static keyword in front of the method definition.
  • Try following method in ‘Room’ class to display total windows.
static void displayTotalWindows()
{
System.out.println("Total Windows: " + totWindows);
}
  • Class variables and class methods can be accessed outside the class using
    <classname> <class variable / method name>
  • For example : Room.totWindows,
    Room.displayTotalWindows ()
  • Note that class members (variables and methods) can be referred without class name by the methods of the same class as shown in code listing of figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 2

  • The output of the code shown in figure is given in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 3

  • Here, an additional instance method setWindowsO has been written, that updates total windows by subtracting the old number of windows and adding new number of windows in a room.
  • Method setWindows is defined in the same class. So it can access class variable totWindows without class name. In main() method (defined in RoomDemoStatic class) that is defined outside ’Room’ class, class variable totWindows is to be accessed as Room.totWindows using class name.
  • Class methods are global to the class itself and available to any other classes or objects.
  • Therefore, class methods can be used anywhere regardless of whether an instance of the class exists or not.
  • The methods that operate on a particular object, or affect that object, should be defined as instance methods. Methods that provide some general utility but do not directly affect an instance of the class are better declared as class methods.
  • For example, consider a function that determines whether a given number is prime or not.
  • This function should be defined as class method.
  • The code listing and its output is shown in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 4

  • The designers of Java have already provided a large number of built-in classes with such class methods.
  • The static and the non-static portions of a class serve different purposes.
  • The static definitions in the source code specify the things that are part of the class itself; whereas the non-static definitions in the source code specify the things that will become part of every instance object belonging to a class.

Points to Remember :

  • Class variables and class methods can be accessed using a class name or reference variable. To increase readability, it is advised to access with class name.
  • Class variables and class methods can be accessed from instance methods also.
  • Instance variables and instance methods can’t be accessed from class methods, as class methods do not belong to any object.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Constructors

  • Constructor is a special kind of method that is invoked when a new object is created.
  • Constructor can perform any action; but it is mainly designed to perform initializing actions.
  • Till now, classes without user-defined constructors have been used.
  • Every class is having its default constructor; sometimes referred to as no-argument constructor.
  • Default constructor does not take any argument.
  • It initializes the attributes of a newly created object using default values based on their data types.
  • Constructor differs from general methods in the following ways :
    1. Constructor must have the same name as class name.
    2. Constructor does not have return type.
    3. Constructor is invoked implicitly only when an object is constructed using new operator.
    4. Constructor cannot be invoked explicitly elsewhere in the program.
  • Like other methods, constructor can also be overloaded. It is possible with varying list of parameters.
  • For example, own constructors can be written to initialize the attributes of ‘Room’ object with different parameters as follows :
  • Room(float 1, float w, float h, byte n) : To initialize length to 1, width to w, height to h and nWindows to n.
  • Room(float 1, float w): To initialize length to 1, width to w, height to 10, nWindows to 1.
  • Program seen in figure shows the use of constructors.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 5

  • In absence of user-defined constructors in a class, objects are constructed using default no-argument constructor.
  • It initializes the attributes using default values.
  • In presence of user-defined constructors in a class, default constructor is no more available.
  • An attempt to create an object using constructor without arguments, compiler returns an error.
  • To solve this problem, we need to provide a user-defined no-argument constructor as follows: <classname>( ) { };
  • In code listing given in figure try to create a room object in main method as follows and observe an error occurred during compilation: Room r3 = new Room();
  • To solve this error, add user-defined no-argument constructor ‘Room ( ) { };’ and execute.
  • The successful execution can be seen in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 6

Question 4.
Write about accessor and mutator methods.
Answer:

  • When access to data is restricted by declaring them as private, the purpose is to protect them from getting directly accessed or modified by methods of other class. If the requirement is there that such data has to be used by others, then “accessor” methods have to be written. If the requirement is there that such data has to be modified by others, then “mutator” methods have to be written.
  • Conventionally, naming of accessor and mutator methods is to capitalize the first letter of variable name and then prepend the variable name with the prefixes get and set respectively.
  • Due to this convention, accessor methods are also known as “getter” and mutator methods as “setter”
  • Observe the code listing shown in figure, “getter” methods getLength() and getWidth() have been used. If the type of variable ‘length’ is changed, it will be hidden from other users.
  • It affects only the implementation of accessor method ‘getLength()’. “getter” methods should be used to allow other methods to read only the data value, “setter” methods should be used to allow other methods to modify the data value.
  • For example, ‘setLength()’ method can be defined to set the value of ‘length’ attribute using passed argument as follows :
    void setLength(float 1) { length = l;}
  • Use of accessor and mutator methods will prevent the variables from getting directly accessed and modified by other users of the class.
  • It may seem a little difficult to get used to this as there will be a need to write get and set method for each and every instance variable. But this minor inconvenience ensures an ease of reusability and maintenance.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Question 5.
How can a superclass constructor be invoked from the sub class ?
Answer:
Constructors

  • Constructor is a special kind of method that is invoked when a new object is created.
  • Constructor can perform any action; but it is mainly designed to perform initializing actions.
  • Till now, classes without user-defined constructors have been used.
  • Every class is having its default constructor; sometimes referred to as no-argument constructor.
  • Default constructor does not take any argument.
  • It initializes the attributes of a newly created object using default values based on their data types.
  • Constructor differs from general methods in the following ways :
    1. Constructor must have the same name as class name.
    2. Constructor does not have return type.
    3. Constructor is invoked implicitly only when an object is constructed using new operator.
    4. Constructor cannot be invoked explicitly elsewhere in the program.
  • Like other methods, constructor can also be overloaded. It is possible with varying list of parameters.
  • For example, own constructors can be written to initialize the attributes of ‘Room’ object with different parameters as follows :
  • Room(float 1, float w, float h, byte n) : To initialize length to 1, width to w, height to h and nWindows to n.
  • Room(float 1, float w): To initialize length to 1, width to w, height to 10, nWindows to 1.
  • Program seen in figure shows the use of constructors.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 5

  • In absence of user-defined constructors in a class, objects are constructed using default no-argument constructor.
  • It initializes the attributes using default values.
  • In presence of user-defined constructors in a class, default constructor is no more available.
  • An attempt to create an object using constructor without arguments, compiler returns an error.
  • To solve this problem, we need to provide a user-defined no-argument constructor as follows: <classname>( ) { };
  • In code listing given in figure, try to create a room object in main method as follows and observe an error occurred during compilation: Room r3 = new Room();
  • To solve this error, add user-defined no-argument constructor ‘Room ( ) { };’ and execute.
  • The successful execution can be seen in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 6

Question 6.
How can an overridden method of superclass be invoked from the sub class ?
Answer:

  • In the previous example, all instances have package visibility. So they are available for direct use in the entire package. If rl, length or crl.width is accessed directly in main() method, there will not be any error.
  • If the visibility of instance variables of superclass is changed to private, these variables are not directly accessible outside the class.
  • Remember that these attributes belongs to sub class also, but still private instance variables or methods are not visible even in its sub class.
  • Modify declaration of instance variables in code listing 8.2 to make them private as follows and observe an error in output as shown in figure private float length, width, height private byte nWindows

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 7
Remember that private members are directly available only in the class in which they are defined and nowhere else. To make them available elsewhere, use public accessor and mutator methods; ‘getter’ and ‘setter’ methods.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Question 7.
Write a short note on ‘Access modifiers.’
Answer:
Visibility Modifiers for Access Control

  • Access control is about controlling visibility. So, access modifiers are also known as visibility modifiers.
  • If a method or variable is visible to another class, then only it can be referred in another class.
  • To protect a method or variable from such references, use the four levels of visibility to provide necessary7 protection.
  • The Four P’s of Protection are public, package (default protection), protected and private.
  • Access modifiers public, protected and private are used before the type of variable or method.
  • When no modifier is used, it is the default one having visibility only within a package that contains the class.
  • Package is used to organize classes. To do so, package statement should be added as the first non-comment or non-blank line in the source file.
  • When a file does not have package statement, the classes defined in the file are placed in default package.
  • Package statement has following syntax :
    package < packageName>;
  • Table 8.1 shows the type of access modifier and its visibility.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 8

Question 8.
Explain the use of inheritance and composition or aggregation based on type of relationship between classes.
Answer:

  • Composition and aggregation are the construction of classes that incorporate other objects. They establish a “has-a” relationship between classes.
  • For example, if class ‘Library’ has been defined, it has a reading room.
  • Here reading room is an object of the class ‘Room’. Thus Library has a Room. When a class includes objects of other class, it is also referred as container class.
  • Other examples :
    1. Person has a name, address. Here, name is of the class Name with three attributes first name, middle name and last name; address is of class Address with attributes house number, apartment/society name, area, city, state, country, pin code.
    2. Car has a steering, wheels and engine. Here steering is of the class Steering, wheel is of the class Wheel and engine is of the class Engine. All the three attributes of class Car are components or parts of a car.
  • Now create class ‘Library’ that contains following attributes :
    1. nBooks: int, number of books in library
    2. nMagazines: int, number of magazines subscribed in library
    3. nNewrspapers: int, number of newspapers subscribed in library
    4. readingRoom: Room
  • The readingRoom is not of the basic data types. It is of the type ‘Room’ class. Code listing shows the
    code to create class named Room and Library and use them in application named ‘Container.java’.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 10

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 11

  • Observe the following points in code listing.
  • In main() method of class ‘Container’ :
    1. An object lib of class ‘Library’ is created using a constructor with four arguments.
    2. Last argument is rl of class ‘Room’.
    3. Method display() of class ‘Library’ is invoked using lib object.
  • In ‘Library’ class :
    1. An object readingRoom is an attribute of class ‘Room’
    2. Constructor with four arguments uses last argument ‘r’ of the class ‘Room’, assigns the values of Room attributes using an assignment statement ‘readingRoom =r;’
    3. Defines display() method which invokes display() method of ‘Room’ class using ‘readingRoom. display();’.
    4. Note that display() method is not overridden; Inheritance has not been used.
    5. Another name can be used for this method, say show() in class ‘Library’ and use ‘lib.show()’ in main() method instead of ‘lib.display()’.
  • Note : ‘Library’ is not of the type ‘Room’. There is no ‘is-a’ relationship between ‘Library’ and ‘Room’. There is ‘has-a’ relationship; ‘Library’ has a ‘Room’ used as reading room. So readingRoom of type ‘Room’ as an attribute of class Library has been used.

Question 9.
Explain the difference between method overloading and method overriding.
Answer:

  • Till now we have done two steps of creating objects : Declaration and Instantiation. The third step is Initialization. It requires the use of constructors. The word polymorphism means “many forms”; different forms of methods with same name. In Java, there can be different methods that have the same name but different signature.
  • This is called ‘method overloading’. The method’s signature is a combination of the method name, the type of return value (object or base type), a list of parameters.
  • For example, to find maximum of two integers, maximum of three integers, maximum of three double precision real numbers and so on one requires to perform similar task but on different set of numbers.
  • In such scenario, Java facilitates to create methods with same name but different parameters. Finding maximum does not need creation of any object, so it can be done as static class method.
  • For example :
    static int max(int x, int y) {…}
    static int max(int x, int y, int z) {…}
    static double max(double x, double y, double z){…}
  • The above max methods forms can be tried and use in the application after looking the example of code listing given in figure Here it uses polymorphism to print a line as per specified parameters.
  • Call printlineO without any parameter prints 40 times ‘ = ’ character, prindine(int n) prints n times ‘# ‘ character, whereas printline(int n, char ch) prints n times specified character ch.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 9

  • In the previous example, all instances have package visibility. So they are available for direct use in the entire package. If rl, length or crl.width is accessed directly in main() method, there will not be any error.
  • If the visibility of instance variables of superclass is changed to private, these variables are not directly accessible outside the class.
  • Remember that these attributes belongs to sub class also, but still private instance variables or methods are not visible even in its sub class.
  • Modify declaration of instance variables in code listing to make them private as follows and observe an error in output as shown in figure. private float length, width, height private byte nWindows

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 7

  • Remember that private members are directly available only in the class in which they are defined and nowhere else. To make them available elsewhere, use public accessor and mutator methods; ‘getter’ and ‘setter’ methods.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Question 10.
Choose the correct option from the following :

1) Which of the following defines attributes and methods ?
(A) Class
(B) Object
(C) Instance
(D) Variable
Answer:
(A) Class

2) Which of the following keyword is used to declare Class variables and class methods ?
(A) static
(B) private
(C) public
(D) package
Answer:
(A) static

3) Which of the following operator creates an object and returns its reference ?
(A) dot (.)
(B) new
(C) colon (:)
(D) assignment (=)
Answer:
(B) new

4) Which of the following method can be called without creating an instance of a class ?
(A) Instance method
(B) Class method
(C) Constructor method
(D) All of the above
Answer:
(B) Class method

5) Which of the following refers more than one method having same name but different parameters ?
(A) Overloaded methods
(B) Overridden methods
(C) Duplicate methods
(D) All of the above
Answer:
(A) Overloaded methods

6) Which method is invoked automatically with creation of an object ?
(A) Instance method
(B) Constructor
(C) Class method
(D) All of the above
Answer:
(B) Constructor

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

7) Which of the following is the keyword used to refer a superclass constructor in sub class constructor ?
(A) extends
(B) super
(C) name of the superclass
(D) new
Answer:
(B) super

8) Which of the following is used to invoke an instance method in Java ?
(A) The name of the object, colonC) and the name of the method
(B) The name of the object, dot(.) and the name of the method
(C) The name of the class, colon (:) and the name of the method
(D) The name of the class, dot(.) and the name of the method
Answer:
(B) The name of the object, dot(.) and the name of the method

9) Which of the following is accessible by ‘ instance methods ?
(A) Only instance variables
(B) Only class variables
(C) Both instance variables and class variables
(D) All of the above
Answer:
(D) All of the above

10) When methods in the superclass and sub class have same name and signature, what are they called ?
(A) Overloaded methods
(B) Overridden methods
(C) Inherited methods
(D) All of the above
Answer:
(C) Inherited methods

Computer Class 12 GSEB Notes Chapter 8 Classes and Objects in Java

Introduction

  • A class contains both data (referred to as attributes) and program code (functions referred to as methods).
  • While it is possible to use only a single class in a Java project, this is not a good practice for large applications.
  • When designing software, the entire application should be divided into simpler components that perform logically related tasks.
  • For each such component or module a class can be created.
  • Let us understand the concept of class and object in Java programming through an example of ‘Room’. A room of a house, hostel, hotel or school processes common characteristics. Each room can be uniquely identified by its properties like length, width, height, number of windows, number of doors and direction. For simplicity, let us consider here length, width, height and number of windows.
  • Below given is a Java Code in code listing to create a class named ‘Room’ with the attributes length, width, height nWindows and three methods.
  • The first method will be used to assign values to attributes.
  • The second method will calculate the area, while the third will display its attributes.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 12
Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 13
Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 14

  • In the above listing, code is written to create a class named ’Room1. Thereafter, code is written to create pbjects of class ’Room’ and use its methods. To do so, another class has been created called ‘RoomDemo’ containing main() method. In a source file, these classes may appear in any order.
  • There is a separation between creating ‘Room’ class performing logically related tasks and using this class in application class ‘RoomDemo’. When a program contains two or more classes, only one class can contain the main( ) method. Figure shows the execution of the code in SciTE editor.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 15
Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 16

  • In the given example of RoomDemo application as shown in figure following operations are performed :
    1. Two objects rl and r2 of class Room are created first. They are initialized with default values (Numeric values are zero by default).
    2. Contents of these two objects are displayed using display method.
    3. Invoking setAttr() method with numeric literals as parameters, attributes of room objects are modified for both the objects rl and r2.
    4. The updated contents of two objects are displayed. Finally area of both room objects is displayed. Here area( ) method is invoked to get area.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Class in Java

  • A class is a template for multiple objects with similar features. Classes embody all the features of a particular set of objects.
  • For example, class ‘Room’ is a template for all rooms with their common properties.
  • In Java, a class is defined using class keyword as follows :
class <ClassName>
{
<Variables>
<Methods>
  • Every class the programmer writes in Java is generally made up of two components: attributes and behaviour. Attributes are defined by variables in a class. Behaviour is defined by methods in a class. Methods are used to access or modify attributes.
  • In code listing, a class is defined named ‘Room’ with attributes defined by variables named length, width, height and nWindows; and behaviour by methods named setAttr(), displayO and area().
  • Another class is created just to create an application using ‘Room’ class.

Accessing Instance Variables and Calling Instance Methods

  • Instance variables and instance methods are accessed via objects.
  • They can be referred by using dot (.) operator as follows :
    <object reference>.<instance variable or method>
  • For example, refer to length of room rl using rl.length in a program and invoke method rl. display() that displays attribute values of room rl as can be seen in code listing.
  • The dot (.) here is an operator and associativity of dot operator is from left to right.
  • It should be remembered that data should be protected from such direct access from anywhere in the program.
  • Such protection is possible with the use of access modifiers.
  • When the instance variables are referred within the methods of the same class, there is no need to use dot (.) operator.
  • For example, in code listing, in method display, instance variables are accessed without using dot operator.
  • This is possible because method is invoked using reference variable rl and thus referred instance variables are considered to be of the corresponding object stored at rl.
  • When the programmer declares an object class, object is not created.
  • In this case, reference variable does not refer to any object and its initial value is null by default.
  • Use of such null reference or null pointer is illegal and may raise an exception.
  • So, referring instance variable or invoking method with null reference will give an error.
  • Try the following code :
    Room rl; // null value assigned to reference variable by default
    System.out.println(rl.length); // illegal
    rl.display!); // illegal

Classification of Variables Declared in a Class

  • Local variables : Variables defined inside methods or blocks are called local variables. Formal parameters of the methods are also local variables. They are created when the method or block is started and destroyed when the method or block has completed. Local variables are not initialized by default values.
  • Instance variables : Instance variables are variables defined within a class but outside any method. These variables are allocated memory from heap area when an object is instantiated (created). Instance variables are initialized by default values.
  • Class variables : Class variables are variables defined within a class, outside any method, with the static keyword. These variables are allocated memory only once per class and is shared by all its objects. Class variables are initialized with default values.

Visibility Modifiers for Access Control
(1) Public :

  • Any method or variable is visible to the class in which it is defined.
  • If we want to make it visible to all the classes outside this class, declare the method or variable to have public access.
  • This is the widest possible access.
  • It provides visibility to classes defined in other package also.
  • To provide public access, use access modifier public before type of variable or method.
  • For example :
    public float length
    public double area( )
  • Note that public variables and methods are visible anywhere and thus can be accessed from other source files and packages also public keyword has been used with main() method to make it available to everyone.
    public static void main(String[] args) { … }

(2) Package (without any modifier) :

  • This is the next level of access that has no precise name.
  • It is indicated by the lack of any access modifier keyword in a declaration.
  • This is the default level of protection.
  • The scope is narrower than public variables.
  • The variable or method can be accessed from anywhere in the package that contains the class, but not from outside that package.
  • Note that a source file without package statement is considered as a package by default.
  • Refer the program showed in figure.
  • Here ‘Rectangle’ class has two attributes: length and width.
  • It also has various methods.
  • Modifier keyword has not used, so there is a package protection by default.
  • Due to this reason, they are directly accessible in another class ‘RectangleDemo’ defined in the same source file (default package).

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 17

(3) Protected :

  • This level of protection is used to allow the access only to subclasses or to share with the methods declared as “friend”. Thus the visibility is narrower than previous two levels; but wider than full privacy provided by fourth level “private”.
  • Use of protected protection will become more relevant when we use inheritance concept of object-oriented programming.

(4) Private :

  • Highest level of protection can be achieved by using “private” protection level. This provides the narrowest visibility.
  • The private methods and variables are directly accessible only by the methods defined within a class. They cannot be seen by any other class.
  • They may seem extremely restrictive, but it is, in fact, a commonly used level of protection.
  • It provides data encapsulation; hiding data from the world’s sight and limiting its manipulation.
  • Anything that shouldn’t be directly shared with anyone including its subclass is private.
  • The best way to provide data encapsulation is to make as much data as private as possible.
  • It separates design from implementation, minimizes the amount of information one class needs to know about another to get its job done.
  • Modify the code listing in figure and declare length and width as private. As private members are directly available only within the same class, it does not give any error when accessed in areaO or display() method.
  • When they are accessed in main() method of RectangleDemo class, it will show an error.
  • The modified code is shown in figure Here, the constructors have been used in addition to private instance variables.
  • Note the error in the output pane says ‘length has private access in Rectangle’. This means that it is not Accessible in class ‘RectangleVisibility1’.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 18

  • The problem now is how to access private variables from another class ?
  • It can be made available indirectly by the methods that are accessible by another class.
  • For explanation, see code listing in figure.
  • Here, two methods have been added: getLength() and getWidth().
  • As no modifier is used, they have package visibility and therefore, directly available in another class, ‘ VisibilityPrivateB’.
  • Through these methods, the values can be derived of private ‘length’ and ‘width’ data fields (instance variables).
  • The use of getLengthO and getWidthO method can be seen while they call in a last output statement in main() method of class VisibilityPrivateB’

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 19

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Passing Object as a Parameter in a Method

Just like variables of primitive data types and available built-in data types, objects can also be passed as parameters in a method.

For example, we want to determine whether the area of invoking rectangle object is larger than another rectangle or not. For this, a method can be written where another rectangle object is passed as an argument or parameter.

Add method ‘isLarge’ in ‘Rectangle’ class as shown in figure and use it in main() method, boolean isLarge(Rectangle rect)
{ if(area() > rect.areaQ ) return true; else return false; }

See the method call in if statement in the mainO method as shown in figure : recti .isLarge (rect2). Here ‘recti’ is a calling or invoking object and ‘rect2’ is an object passed as parameter. In the isLarge() method, area() refers to area or calling object ‘recti’ and rect.areaQ refers to area of an object passed as argument.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 20

Remember that parameters of primitive types are passed by value. The values of actual parameters are copied to formal parameters and then function is executed. Changes made to formal parameters are not affecting actual parameters. It should be noted that object parameters are passed by reference. So, whatever modifications are performed to the object inside the method, the original object is affected as well. Here, an address (and not value) of the actual parameter is copied to formal parameter.

Inheritance

  • Object-oriented programming languages provide reusability feature using inheritance.
  • Inheritance allows us to build new class with added capabilities by extending existing class. Inheritance models ‘is-a’ relationship between two classes.
  • For example, classroom is a room, student is a person. Here, room and person are called parent class; classroom and student are called child classes.
  • Parent class is also referred to as superclass or base class. In the same way; child class is also referred to as sub class, derived class or extended class.
  • Whenever two classes have ‘is-a’ relationship, inheritance is used. Common features are kept in superclass.
  • A sub class inherits all instance variables and methods from superclass and it may have its own added variables and methods.
  • Note that constructors are not inherited in sub class. For example, like room, classroom also has variables length, width, height, number of windows.
  • In addition, it has number of benches and capacity of each bench to accommodate students. Similarly, sub class inherits all methods of superclass and it may have additional methods.
  • Here, sub class Classroom has additional methods: show(), display(), getSeats() and its constructor methods.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 21

  • Figure shows a class diagram that has a class named ‘Classroom’ derived from its parent class named ‘Room’. See that the arrow points from sub class towards superclass. In sub class, only additional attributes and methods are to be shown.
  • Note that a sub class is not a subset of superclass. In fact, sub class usually contains more information and methods than its superclass.
  • When an object of sub class is instantiated, memory is allocated for all its attributes including inherited ones.
  • Figure shows the instances of superclass Room and sub class Classroom.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 22

  • In Java, to create a sub class, keyword ‘extends’ is used in the class definition.
  • Code listing shows creation of sub class ‘Classroom’ using existing class ‘Room’.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 23

  • Now, add code to create a sub class ‘Classroom1 by extending superclass ‘Room’ as shown in code listing.
  • Sub class has two additional instance variables nBenches and and nSeatsBench.
  • Variable nSeatsBench denotes the number of students that can seated on one bench.
  • It has its own additional constructors and three methods: show(), display() and getSeats().

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 24

  • In sub class ‘Classroom’, user defined constructor and method showO have reused the code written in superclass ‘Room’.
  • As constructors of a superclass are not inherited in the sub class, keyword ‘super’ is used to call the constructor of superclass in the constructor of sub class. This call must be the first statement in the constructor.
  • When there is no explicit call to constructor of superclass, no-argument constructor of superclass is implicitly called as the first statement ‘super()’.
  • Method show() is used to display attributes of classroom object. To display first four attributes inherited from superclass ‘Room’, we want to use existing code in display() method of superclass.
  • Now display() method is available in sub class also. In show(), our intention is call display() method of superclass. To do so, super.display() has been used.
  • When superclass and sub class have methods with same signature, a superclass method is said to be overridden in the sub class.
  • Method display() in sub class is used to override display() method of superclass. It means that the programmer wants to display the details in a different way without reusing the display!) method of superclass.
  • When such method of superclass is to be referred, the keyword ‘super’ has to be used with dot operator and method name.
  • In this program, super.display() has been used in show() method to invoke display() method of superclass. Method getSeats() is used to compute the seating capacity of a classroom.
  • In code listing, objects have been created of both superclass and sub class.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 25

  • All instance variables and methods are inherited from superclass to sub class.
  • Thus method area() of superclass can be invoked using an object of sub class also crl.area().
  • When overridden method is referred in an application using sub class object, it calls the method of sub class as cr2.display!).
  • The output of the code created by combining code 8.2, 8.3 and 8.4 is shown in figure.

Computer Class 12 GSEB Solutions Chapter 8 Classes and Objects in Java 26

Protected Members of Superclass

  • As studied before in the topic ‘Visibility Modifiers’, ‘protected’ members are available as ’private’ members in the inherited sub class.
  • Modify the instance variables of class ‘Room’ to protected as follows :
    protected float length, width, height; protected byte nWindows;
  • When the modified code is executed the result will be same as shown in figure. It is to be noted that Java does not support multiple inheritance. A sub class can be derived from only one superclass.

Leave a Comment

Your email address will not be published. Required fields are marked *