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

Java ASSIGNMENT 2 Answer Key - Set 2 (Exam Format)

The document discusses key concepts of Java such as Inheritance, Polymorphism, Method Overriding, and their examples. It explains the differences between method overloading and overriding, types of inheritance, and the role of constructors in inheritance. Additionally, it covers the use of final classes, abstract classes, and methods, along with the significance of the super keyword in method overriding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java ASSIGNMENT 2 Answer Key - Set 2 (Exam Format)

The document discusses key concepts of Java such as Inheritance, Polymorphism, Method Overriding, and their examples. It explains the differences between method overloading and overriding, types of inheritance, and the role of constructors in inheritance. Additionally, it covers the use of final classes, abstract classes, and methods, along with the significance of the super keyword in method overriding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Java ASSIGNMENT 2 Answer Key - Set 2 (Based on Provided Notes - Exam

Format)
1. Explain the concepts of Inheritance and Polymorphism. Provide an example of
method overriding.
●​ Inheritance:
○​ Concept: According to the notes, Inheritance is defined as the procedure or
mechanism where one class (subclass or derived class) acquires all the
properties and behavior of another class (parent class). It facilitates code
reusability by allowing new classes to be built upon existing ones [cite: 12].
●​ Polymorphism:
○​ Concept: The notes define Polymorphism as meaning "having multiple forms"
(from Greek: poly=many, morphos=forms). It's a feature of OOPs where a
single interface can have multiple implementations. The underlying approach
is "single interface with multiple implementations" [cite: 14].
●​ Example of Method Overriding:​
(The following example demonstrates method overriding, based on snippets
found in the notes) [cite: 17]​
class Animal {​
void eat() {​
System.out.println("eating...");​
}​
}​

class Dog extends Animal {​
// Overriding the eat() method of the Animal class​
@Override // Optional annotation, good practice​
void eat() {​
System.out.println("eating bread...");​
}​

void bark() {​
System.out.println("barking...");​
}​

void work() {​
// Calling the overridden parent class method using super​
super.eat();​
bark();​
}​
}​

class TestSuper2 {​
public static void main(String args[]) {​
Dog d = new Dog();​
d.eat(); // Calls the Dog's overridden eat() method​
d.work(); // Calls work, which calls super.eat() and bark()​
}​
}​

Output:​
eating bread...​
eating...​
barking...​

2. Describe method overriding in Java.

Method overriding occurs when a subclass (child class) provides a specific


implementation for a method that is already defined in its superclass (parent class).
The method in the subclass must have the same name, same parameters (number,
type, and order), and same return type (or a subtype) as the method in the
superclass. One major advantage noted is that a class can provide its own specific
execution without modifying the parent class [cite: 16]. The example provided in
Question 1 demonstrates overriding the eat() method.

3. Differentiate between method overloading and method overriding.

While a direct comparison table is not present in the retrieved snippets, the concepts
can be differentiated based on their definitions and examples found in the notes:
●​ Method Overloading:
○​ Occurs within the same class.
○​ Involves multiple methods having the same name but different parameters
(different number, type, or order of arguments).
○​ It is an example of compile-time (static) polymorphism.
○​ Return type can be different.
○​ Example: The Adder class with add(int, int) and add(double, double) methods
[cite: 18].
●​ Method Overriding:
○​ Occurs between a superclass and a subclass (inheritance relationship is
required).
○​ The method in the subclass has the same name and the same parameters as
the method in the superclass.
○​ It is an example of runtime (dynamic) polymorphism.
○​ The return type must be the same or a covariant type.
○​ Used to provide a specific implementation in the subclass.
○​ Example: The Dog class overriding the eat() method from the Animal class
[cite: 17].
4. Discuss how the usage of final variables and final method together
contributes to immutable classes.

The provided notes mention final as a non-access modifier [cite: 1] and state that
interfaces have static and final variables [cite: 21]. However, the detailed usage of final
variables (to make them constants after initialization) and final methods (to prevent
overriding) and how these specifically contribute to creating immutable classes
(classes whose state cannot be changed after creation) is not detailed in the
retrieved sections of the notes.

5. Can an abstract class have a final method? Justify your answer.

The retrieved notes compare abstract classes and interfaces, mentioning that abstract
classes can have final variables [cite: 21]. However, the specific rule regarding whether an
abstract class can contain a final method is not explicitly stated in the available snippets.
(General Java Rule: Yes, an abstract class can have final methods. abstract applies to
methods that must be implemented by subclasses, while final applies to methods that cannot
be overridden. An abstract class can provide some concrete, non-overridable functionality via
final methods.)
6. Describe types of Inheritance with suitable program.

Inheritance allows a class to inherit properties and behaviors from another class. The
notes mention [cite: 12, 13]:
●​ Concept: Acquiring properties/behavior from a parent class to a child class for
code reusability.
●​ Types Mentioned/Implied:
○​ Single Inheritance: (Not explicitly named but fundamental) A subclass
inherits from one superclass.
○​ Multilevel Inheritance: (Implied by structure possibilities) A class inherits
from a derived class, forming a chain.
○​ Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass. The homeTution extends Student example, if combined with
Student extends Teacher [cite: 13], illustrates this (assuming homeTution and
Student both extend Teacher, though the example code structure is slightly
unclear in the snippet).
○​ Multiple Inheritance (via Classes): The notes state that Java reduces
ambiguity issues found in multiple inheritance (inheriting from more than one
class) by using interfaces instead [cite: 14]. So, multiple inheritance through
classes is generally not supported directly.
●​ Example Program (Illustrating Single/Hierarchical based on snippets):​
(Note: The example code in snippet 13 seems incomplete/has typos. The following
combines concepts)​
class Teacher { // Superclass​
void teach() {​
System.out.println("Teaching subject");​
}​
}​

class Student extends Teacher { // Subclass inheriting from Teacher (Single
Inheritance)​
void listen() {​
System.out.println("Listening");​
}​
}​

// Assuming homeTution also extends Teacher, demonstrating Hierarchical​
class HomeTution extends Teacher { // Another subclass inheriting from Teacher​
void explains() {​
System.out.println("Doing homework explanation");​
}​
}​

class InheritanceTest {​
public static void main(String args[]) {​
Student s = new Student();​
s.listen(); // Method from Student​
s.teach(); // Method inherited from Teacher​

HomeTution h = new HomeTution();​
h.explains(); // Method from HomeTution​
h.teach(); // Method inherited from Teacher​
}​
}​

7. Explain How to inherit Data members and methods with suitable example.

When a class inherits from another class (superclass), it automatically acquires


access to the non-private data members (instance variables) and methods of the
superclass, unless they are overridden.
●​ Example:​
class Calculation { // Superclass​
int z; // Data member​

public void addition(int x, int y) { // Method​
z = x + y;​
System.out.println("The sum of the given numbers: " + z);​
}​

public void subtraction(int x, int y) { // Method​
z = x - y;​
System.out.println("The difference between the given numbers: " + z);​
}​
}​

// Subclass inherits data member 'z' and methods 'addition', 'subtraction'​
class MyCalculation extends Calculation {​
public void multiplication(int x, int y) { // Own method​
z = x * y; // Accessing inherited data member 'z'​
System.out.println("The product of the given numbers: " + z);​
}​

public static void main(String args[]) {​
int a = 20, b = 10;​
MyCalculation demo = new MyCalculation();​
demo.addition(a, b); // Calling inherited method​
demo.subtraction(a, b); // Calling inherited method​
demo.multiplication(a, b); // Calling own method​
}​
}​

Output:​
The sum of the given numbers: 30​
The difference between the given numbers: 10​
The product of the given numbers: 200​

8. Describe the Overriding Superclass Methods using of “super”.

The super keyword is a reference variable used to refer to the immediate parent class
object [cite: 16]. When a subclass overrides a method from its superclass, the super
keyword can be used within the subclass's method to explicitly call the overridden
method from the superclass.
●​ Usage: super.methodName(arguments);
●​ Example: [cite: 17]​
class Animal {​
void eat() {​
System.out.println("eating...");​
}​
}​

class Dog extends Animal {​
@Override​
void eat() {​
System.out.println("eating bread...");​
}​

void work() {​
// Calling the parent class's eat() method using super​
super.eat();​
System.out.println("Working after eating like parent...");​
}​
}​

class TestSuperMethod {​
public static void main(String args[]) {​
Dog d = new Dog();​
d.work();​
}​
}​

Output:​
eating...​
Working after eating like parent...​

9. Describe role of constructors in inheritance.

Constructors are used to initialize objects. In inheritance, when a subclass object is


created, the constructor of the superclass is implicitly invoked first, before the
subclass constructor executes. The super() keyword call is used for this purpose.
●​ super() Keyword: The notes state that super() can be used to invoke the
immediate parent class constructor [cite: 16].
●​ Implicit Call: If the programmer does not explicitly add super() as the first
statement in the subclass constructor, the compiler implicitly adds a call to the
superclass's no-argument constructor (super();).
●​ Explicit Call: If the superclass does not have a no-argument constructor, or if a
specific superclass constructor needs to be called, the programmer must
explicitly call super(arguments) as the very first statement in the subclass
constructor.
(Note: A specific code example demonstrating super() usage in constructors was not
found in the retrieved snippets [cite: 16, 17].)

10. Explain the concepts of polymorphism with Example.

Polymorphism means "many forms". In Java, it's an OOP concept allowing objects of
different classes to be treated as objects of a common superclass, primarily through
method overriding (runtime polymorphism) or method overloading (compile-time
polymorphism). It allows a single action or method name to behave differently
depending on the object performing the action or the context in which it's called [cite:
14].
●​ Example (Illustrating Runtime Polymorphism):​
class Shape {​
void draw() {​
System.out.println("Drawing a shape");​
}​
}​

class Circle extends Shape {​
@Override​
void draw() {​
System.out.println("Drawing a circle");​
}​
}​

class Square extends Shape {​
@Override​
void draw() {​
System.out.println("Drawing a square");​
}​
}​

class TestPolymorphism {​
public static void main(String args[]) {​
Shape s; // Reference of type Shape​

s = new Circle(); // s refers to a Circle object​
s.draw(); // Calls Circle's draw() method​

s = new Square(); // s refers to a Square object​
s.draw(); // Calls Square's draw() method​

s = new Shape(); // s refers to a Shape object​
s.draw(); // Calls Shape's draw() method​
}​
}​

Output:​
Drawing a circle​
Drawing a square​
Drawing a shape​

11. Describe the types of Polymorphism with programs.

Java exhibits two main types of polymorphism:


1.​ Compile-time Polymorphism (Static Polymorphism):
○​ Achieved through Method Overloading.
○​ The decision of which method to call is made at compile time based on the
method signature (name and parameter list).
○​ Example Program (Method Overloading): [cite: 18]​
class Adder {​
static int add(int a, int b) {​
System.out.print("Adding two ints: ");​
return a + b;​
}​

static int add(int a, int b, int c) {​
System.out.print("Adding three ints: ");​
return a + b + c;​
}​

static double add(double a, double b){​
System.out.print("Adding two doubles: ");​
return a+b;​
}​
}​

class TestOverloading {​
public static void main(String[] args) {​
System.out.println(Adder.add(11, 11));​
System.out.println(Adder.add(11, 11, 11));​
System.out.println(Adder.add(12.3, 12.6));​
}​
}​

Output:​
Adding two ints: 22​
Adding three ints: 33​
Adding two doubles: 24.9​

2.​ Runtime Polymorphism (Dynamic Polymorphism):


○​ Achieved through Method Overriding.
○​ The decision of which overridden method to call is made at runtime based on
the actual object type referred to by the reference variable. This is also known
as dynamic method dispatch.
○​ Requires an inheritance relationship (IS-A).
○​ Example Program (Method Overriding): [cite: 19]​
class Vehicle {​
void run() {​
System.out.println("Vehicle is running");​
}​
}​

class Bike extends Vehicle {​
@Override​
void run() {​
System.out.println("Bike is running safely");​
}​
}​

class TestRuntimePoly {​
public static void main(String args[]) {​
Vehicle v = new Bike(); // Upcasting: Vehicle reference refers to Bike
object​
v.run(); // Calls Bike's run() method at runtime​
}​
}​

Output:​
Bike is running safely​

12. Describe the final Classes and finalize Methods with example.
●​ final Classes:
○​ The notes mention final as a non-access modifier [cite: 1]. If a class is
declared final, it cannot be subclassed (inherited from).
○​ (A specific definition or example of a final class was not found in the retrieved
snippets.)
●​ finalize Methods:
○​ The finalize() method is not mentioned in the retrieved snippets from the
provided notes.
○​ (General Java Info: finalize() is a protected method of the Object class. The
garbage collector calls it on an object just before reclaiming its memory. Its
use is discouraged and it has been deprecated because its invocation is not
guaranteed.)
13. Explain the abstract classes and Methods with example.
●​ Abstraction Concept: The notes define abstraction as a process of hiding
implementation details and showing only functionality to the user [cite: 19].
●​ Abstract Classes and Methods:
○​ An abstract class is a class declared with the abstract keyword. It cannot be
instantiated directly (you cannot create objects of an abstract class). It can
contain both abstract methods and concrete (non-abstract) methods.
○​ An abstract method is a method declared with the abstract keyword and has
no implementation (no body, ends with a semicolon). Subclasses that inherit
from an abstract class must provide implementations for all its abstract
methods, unless the subclass is also declared abstract.
○​ The notes mention that abstract classes can have various types of variables
(final, non-final, static, non-static) [cite: 21] and can provide the
implementation of an interface [cite: 21]. Interfaces are described as having
static final constants and abstract methods [cite: 20].
○​ (A specific code example defining an abstract class and abstract method was
not found in the retrieved snippets.)
14. Write a program of given scenario using Run time Polymorphism.
Scenario: Bank class with getRateOfInterest(). Subclasses SBI, ICICI, AXIS override it with
rates 8.4%, 7.3%, 9.7%.
The specific Bank scenario example (SBI, ICICI, AXIS) is not present in the retrieved
snippets of the notes. However, the principle of runtime polymorphism via method
overriding is demonstrated in the notes (e.g., Vehicle/Bike example [cite: 19],
Animal/Dog example [cite: 17]).

Based on the principles shown in the notes, a program for the Bank scenario would
look conceptually like this:

// Concept based on notes, specific example not found​


class Bank {​
float getRateOfInterest() {​
return 0; // Default rate​
}​
}​

class SBI extends Bank {​
@Override​
float getRateOfInterest() {​
return 8.4f;​
}​
}​

class ICICI extends Bank {​
@Override​
float getRateOfInterest() {​
return 7.3f;​
}​
}​

class AXIS extends Bank {​
@Override​
float getRateOfInterest() {​
return 9.7f;​
}​
}​

class TestBankPolymorphism {​
public static void main(String args[]) {​
Bank b; // Superclass reference​

b = new SBI();​
System.out.println("SBI Rate of Interest: " + b.getRateOfInterest()); // Calls SBI's
method​

b = new ICICI();​
System.out.println("ICICI Rate of Interest: " + b.getRateOfInterest()); // Calls ICICI's
method​

b = new AXIS();​
System.out.println("AXIS Rate of Interest: " + b.getRateOfInterest()); // Calls AXIS's
method​
}​
}​

15. How to write a program of Method Overloading and Method Overriding


explain with example.
●​ Method Overloading:
○​ Explanation: Define multiple methods within the same class that share the
same name but have different parameter lists (differing in number, type, or
order of parameters).
○​ Example: (See Adder class in Question 11 [cite: 18])​
class OverloadDemo {​
void display(int a) {​
System.out.println("Displaying int: " + a);​
}​
void display(String s) {​
System.out.println("Displaying String: " + s);​
}​
void display(int a, double b) {​
System.out.println("Displaying int and double: " + a + ", " + b);​
}​
// ... main method to call these ...​
}​

●​ Method Overriding:
○​ Explanation: Create a subclass that inherits from a superclass. In the
subclass, define a method that has the exact same name and parameter list
as a method in the superclass. This provides a specialized implementation in
the subclass.
○​ Example: (See Animal and Dog classes in Question 1 [cite: 17] or Vehicle and
Bike classes in Question 11 [cite: 19])​
class Parent {​
void show() {​
System.out.println("Parent's show()");​
}​
}​
class Child extends Parent {​
@Override // Optional but good practice​
void show() { // Overriding method​
System.out.println("Child's show()");​
}​
// ... main method to demonstrate ...​
}​

You might also like