Assignment-2
1. How do you pass arguments to superclass constructor
through the subclass constructor? Explain with code
Snippet.
Ans:
To pass arguments to a superclass constructor through a
subclass constructor in Java, you use the super keyword.
This keyword allows you to call a constructor from the
superclass and pass the necessary parameters. It must
be the first statement in the subclass constructor.
Example:
// Superclass
class Person {
private String name;
// Constructor of Person class
public Person(String name) {
this.name = name;
System.out.println("Person's name: " + this.name);
// Subclass
class Employee extends Person {
private int id;
// Constructor of Employee class
public Employee(String name, int id) {
super(name); // Call to superclass constructor with
name
this.id = id;
System.out.println("Employee ID: " + this.id);
// Main class to test the constructors
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("Alice", 101);
Explanation:
1. Superclass (Person): It has a constructor that takes
a String argument to initialize the name.
2. Subclass (Employee): Its constructor takes two
parameters: a String for the name and an int for the
ID. The first line of the Employee constructor calls
the Person constructor using super(name), passing the
name argument.
3. Output: When you create an instance of Employee, it
first initializes the Person part of the object, printing
"Person's name: Alice", followed by "Employee ID: 101".
2. Explain the following keywords.
a) This
Ans: The this keyword in Java is a reference variable
that refers to the current object. It is commonly used in
the following scenarios:
• Disambiguation: When local variables (like parameters)
have the same name as instance variables, this is used
to distinguish between them.
• Constructor Chaining: It can be used to call another
constructor in the same class.
• Passing the Current Object: It can be passed as an
argument to methods or constructors.
Example:
class Example {
private int value;
public Example(int value) {
this.value = value; // 'this.value' refers to the
instance variable
b) Super
Ans: The super keyword is used to refer to the
immediate parent class object. It serves several
purposes:
• Access Parent Class Variables: It allows access to
parent class instance variables when there is a name
conflict.
• Invoke Parent Class Methods: It can be used to call
methods from the parent class that may have been
overridden.
• Call Parent Class Constructor: It is used to invoke the
constructor of the parent class.
Example:
class Parent {
public Parent() {
System.out.println("Parent constructor");
class Child extends Parent {
public Child() {
super(); // Calls Parent constructor
System.out.println("Child constructor");
c) Final
Ans: The final keyword in Java is a non-access modifier
that can be applied to variables, methods, and classes,
indicating that they cannot be changed or overridden:
• Final Variables: Once assigned, their values cannot be
modified.
• Final Methods: They cannot be overridden by
subclasses.
• Final Classes: They cannot be subclassed.
Example:
final class FinalClass {
final int constantValue = 10; // Cannot change this
value
d) Static:
Ans: The static keyword indicates that a particular
member belongs to the class rather than instances of the
class. It has several uses:
• Static Variables: Shared among all instances of a
class.
• Static Methods: Can be called without creating an
instance of the class and can only access static
variables and methods directly.
• Static Blocks: Used for static initialization of a class.
Example:
class StaticExample {
static int count = 0; // Static variable
static void increment() { // Static method
count++;
}
3. What do you mean by method overriding? Discuss with
a programming example
Ans: Method overriding in Java occurs when a subclass
provides a specific implementation for a method that is
already defined in its superclass. This allows the subclass
to modify or extend the behavior of that method without
changing the superclass's code. Method overriding is a
key feature of polymorphism in object-oriented
programming, enabling dynamic method dispatch.
Key Points of Method Overriding
• Same Method Signature: The method in the subclass
must have the same name, return type, and parameters
as the method in the superclass.
• Use of @Override Annotation: While not mandatory,
using this annotation helps to inform the compiler that
you intend to override a method. If the method does
not actually override any method from the superclass,
the compiler will raise an error.
• Access Modifiers: The access level of the overriding
method can be less restrictive than that of the
overridden method.
Example:
// Superclass
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
// Subclass
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
// Main class to test overriding
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal
reference and object
Animal myDog = new Dog(); // Animal reference but
Dog object
myAnimal.sound(); // Outputs: Animal makes a sound
myDog.sound(); // Outputs: Dog barks (overridden
method)
Explanation of the Example:
1. Superclass (Animal): It has a method sound() that
prints a general message.
2. Subclass (Dog): It overrides the sound() method to
provide a specific implementation that indicates a dog
barks.
3. Main Class: In the main method, both an Animal object
and a Dog object are created. When calling sound() on
each, it demonstrates how the Dog class's
implementation overrides that of Animal.
4. Explain abstract class and abstract method with
suitable code snippet.
Ans: An abstract class in Java is a class that cannot be
instantiated on its own and is declared using
the abstract keyword. It can contain both abstract
methods (methods without a body) and concrete methods
(methods with an implementation). Abstract classes are
used to provide a base for subclasses to extend and
implement the abstract methods.An abstract method is a
method that is declared without an implementation.
Subclasses that extend the abstract class must provide
concrete implementations for all of its abstract methods
unless they are also declared as abstract.
Key Features of Abstract Classes and Methods
• Cannot be instantiated: You cannot create objects of
an abstract class directly.
• Can contain both abstract and concrete methods:
Abstract classes can have methods with
implementations as well as methods without.
• Subclasses must implement abstract methods: Any
concrete subclass must provide implementations for all
inherited abstract methods.
Example:
// Abstract class
abstract class Animal {
// Abstract method (no body)
public abstract void makeSound();
// Concrete method
public void eat() {
System.out.println("This animal eats food.");
}
// Subclass that extends Animal
class Dog extends Animal {
// Providing implementation for the abstract method
@Override
public void makeSound() {
System.out.println("Dog barks");
// Subclass that extends Animal
class Cat extends Animal {
// Providing implementation for the abstract method
@Override
public void makeSound() {
System.out.println("Cat meows");
// Main class to test the code
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Creating a Dog object
Animal myCat = new Cat(); // Creating a Cat object
myDog.makeSound(); // Outputs: Dog barks
myDog.eat(); // Outputs: This animal eats food.
myCat.makeSound(); // Outputs: Cat meows
myCat.eat(); // Outputs: This animal eats food.
Explanation of the Example:
1. Abstract Class (Animal): This class contains one
abstract method makeSound() and one concrete
method eat().
2. Subclasses (Dog and Cat): Both subclasses
extend Animal and provide their own implementations
of the makeSound() method.
3. Main Class: In the main method, instances
of Dog and Cat are created, demonstrating
polymorphism. The appropriate sound is made when
calling makeSound() on each object.
5. Explain Dynamic Method Dispatch with suitable
programming example
Ans: Dynamic Method Dispatch, also known as runtime
polymorphism, is a mechanism in Java where a method call
to an overridden method is resolved at runtime rather than
compile time. This allows Java to determine which method
implementation to execute based on the actual object type
being referred to, rather than the reference type.
Key Features of Dynamic Method Dispatch
• Run-time Resolution: The method to be executed is
determined at runtime based on the object being
referenced.
• Polymorphism: It enables a single interface to
represent different underlying forms (data types).
• Superclass Reference: A superclass reference can
refer to subclass objects, allowing the use of
overridden methods.
Example:
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass 1
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
// Subclass 2
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
// Main class to test dynamic method dispatch
public class Main {
public static void main(String[] args) {
Animal myAnimal; // Declare an Animal reference
myAnimal = new Dog(); // Assign Dog object
myAnimal.makeSound(); // Outputs: Dog barks
myAnimal = new Cat(); // Assign Cat object
myAnimal.makeSound(); // Outputs: Cat meows
Explanation of the Example:
1. Superclass (Animal): Contains a
method makeSound() that prints a generic sound.
2. Subclasses (Dog and Cat): Each subclass overrides
the makeSound() method to provide specific
implementations.
3. Main Class: In the main method, an Animal reference is
declared. It first points to a Dog object, and
when makeSound() is called, it executes the Dog's
implementation. Then, it points to a Cat object, and
calling makeSound() executes the Cat's implementation.
6. Create an abstract class called Employee. Include the
members: Name, EmpID and an abstract method cal_sal().
Create two inherited classes SoftwareEng (with the
members basic and DA) and HardwareEng (with members
basic and TA). Implement runtime polymorphism
(dynamicmethod dispatch) to display salary of different
employees by creating array of references to superclass.
Ans:
// Abstract class Employee
abstract class Employee {
protected String name;
protected int empID;
// Constructor to initialize name and empID
public Employee(String name, int empID) {
this.name = name;
this.empID = empID;
// Abstract method to calculate salary
public abstract double cal_sal();
// Method to display employee details
public void display() {
System.out.println("Name: " + name);
System.out.println("Employee ID: " + empID);
System.out.println("Salary: " + cal_sal());
// Subclass SoftwareEng
class SoftwareEng extends Employee {
private double basic;
private double da; // Dearness Allowance
// Constructor to initialize SoftwareEng specific
members
public SoftwareEng(String name, int empID, double basic,
double da) {
super(name, empID);
this.basic = basic;
this.da = da;
// Implementing the abstract method to calculate salary
@Override
public double cal_sal() {
return basic + da; // Salary calculation for Software
Engineer
// Subclass HardwareEng
class HardwareEng extends Employee {
private double basic;
private double ta; // Travel Allowance
// Constructor to initialize HardwareEng specific
members
public HardwareEng(String name, int empID, double
basic, double ta) {
super(name, empID);
this.basic = basic;
this.ta = ta;
// Implementing the abstract method to calculate salary
@Override
public double cal_sal() {
return basic + ta; // Salary calculation for Hardware
Engineer
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
// Creating an array of Employee references
Employee[] employees = new Employee[3];
// Initializing the array with different employee types
employees[0] = new SoftwareEng("Alice", 101, 50000,
10000);
employees[1] = new HardwareEng("Bob", 102, 45000,
8000);
employees[2] = new SoftwareEng("Charlie", 103,
60000, 12000);
// Displaying details and salaries of all employees using
dynamic method dispatch
for (Employee emp : employees) {
emp.display();
System.out.println(); // For better readability
}
}
7. What do you mean by a package? How to find Packages
and CLASSPATH? How do you import in a Java program?
Explain with a program.
Ans:
A package in Java is a namespace that organizes a set of
related classes and interfaces. Think of it as a folder in a
file directory that helps to avoid name conflicts and makes
it easier to manage large software projects. Packages can
be classified into two main types: built-in packages
(provided by the Java API) and user-defined packages
(created by developers).
Key Features of Packages
• Namespace Management: Packages provide a unique
namespace for classes, which helps avoid naming
conflicts.
• Access Control: They allow for controlled access to
classes and their members, enhancing encapsulation.
• Organization: Packages help organize classes into a
structured hierarchy, making it easier to locate and
maintain code.
Finding Packages and CLASSPATH
• Packages: You can find available packages in the Java
API documentation. The built-in packages
include java.lang, java.util, java.io, etc.
• CLASSPATH: This is an environment variable that tells
the Java Virtual Machine (JVM) and Java compiler
where to look for user-defined classes and packages.
You can set the CLASSPATH to include directories or
JAR files containing your compiled classes.
Importing Packages
To use classes from a package in your Java program, you
need to import them using the import statement. You can
either import a specific class or all classes from a package.
Syntax:
To import a specific class:
import packageName.ClassName;
To import all classes from a package:
import packageName.*;
9. What are different parameter passing techniques in
Java? Discuss the salient features of the same.
Ans: Parameter Passing Techniques in Java
1. Call-by-Value
In the call-by-value technique, a copy of the actual
parameter's value is passed to the method. This means that
any modifications made to the parameter within the method
do not affect the original value.Salient Features:
• Independent Copies: The method operates on a copy,
so changes do not affect the original variable.
• Used for Primitives: This technique is used for
primitive data types (e.g., int, float, char).
• Example:
2. Call-by-Reference (Conceptual)
Although Java does not support call-by-reference in the
traditional sense, it behaves similarly when passing object
references. In this case, a copy of the reference (memory
address) to the object is passed to the method. Changes
made to the object's attributes within the method reflect
on the original object.Salient Features:
• Reference Copy: A copy of the reference to the
object is passed, allowing modifications to the object's
state.
• Used for Objects: This technique applies to objects
and arrays.
• Example:
11. Define an interface. Explain how to define and
implement an interface with an example
Ans: An interface in Java is a reference type that
defines a contract for classes to implement. It is similar
to a class but can only contain method signatures
(abstract methods) and constants. Interfaces are used to
achieve abstraction and multiple inheritance in Java.
Key Features of Interfaces
• Abstract Methods: All methods in an interface are
implicitly abstract (no body).
• Constants: Fields declared in an interface are
implicitly public, static, and final.
• No Constructors: Interfaces cannot have constructors
as they cannot be instantiated.
• Multiple Inheritance: A class can implement multiple
interfaces, allowing for multiple inheritance of type.
• Default and Static Methods: Since Java 8, interfaces
can also include default methods (with a body) and
static methods.
Defining an Interface
To define an interface, use the interface keyword
followed by the interface name.
Implementing an Interface
A class implements an interface using
the implements keyword. The implementing class must
provide concrete implementations for all abstract
methods defined in the interface.
Example:
// Define the Animal interface
interface Animal {
void eat(); // Abstract method
void travel(); // Abstract method
// Class Dog implementing the Animal interface
class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog eats bones.");
@Override
public void travel() {
System.out.println("Dog runs.");
// Class Cat implementing the Animal interface
class Cat implements Animal {
@Override
public void eat() {
System.out.println("Cat eats fish.");
@Override
public void travel() {
System.out.println("Cat walks gracefully.");
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
myDog.eat(); // Outputs: Dog eats bones.
myDog.travel(); // Outputs: Dog runs.
Animal myCat = new Cat(); // Create a Cat object
myCat.eat(); // Outputs: Cat eats fish.
myCat.travel(); // Outputs: Cat walks gracefully.
}
12. Design Interface called polygon with a method called
area(). Implement this Interface to create different
classes like Square, Rectangle and print the area of
Square and Rectangle.
Ans:
// Define the Polygon interface
interface Polygon {
double area(); // Method to calculate area
// Class Square implementing the Polygon interface
class Square implements Polygon {
private double side;
// Constructor to initialize side length
public Square(double side) {
this.side = side;
// Implementing area method for Square
@Override
public double area() {
return side * side; // Area = side^2
}
// Class Rectangle implementing the Polygon interface
class Rectangle implements Polygon {
private double length;
private double width;
// Constructor to initialize length and width
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
// Implementing area method for Rectangle
@Override
public double area() {
return length * width; // Area = length * width
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
Polygon square = new Square(5); // Create a Square
with side 5
System.out.println("Area of Square: " +
square.area()); // Outputs: Area of Square: 25.0
Polygon rectangle = new Rectangle(4, 6); // Create a
Rectangle with length 4 and width 6
System.out.println("Area of Rectangle: " +
rectangle.area()); // Outputs: Area of Rectangle: 24.0
13. Explain the access protection for packages in Java
with programming examples.
Ans:
Example Programs
14. Discuss the following with Java code snippet.
i) Returning Objects
Ans: Returning Objects in Java
In Java, methods can return objects just like they can
return primitive data types. When a method returns an
object, it provides a way to create and manipulate
complex data structures. This is particularly useful for
encapsulating data and functionality within classes.
Example
// Class representing a simple Point
class Point {
private int x;
private int y;
// Constructor to initialize the point
public Point(int x, int y) {
this.x = x;
this.y = y;
// Method to display the coordinates
public void display() {
System.out.println("Point coordinates: (" + x + ", " + y
+ ")");
// Class with a method that returns a Point object
class PointFactory {
// Method to create and return a Point object
public Point createPoint(int x, int y) {
return new Point(x, y); // Returning a new Point
object
// Main class to test the object return
public class Main {
public static void main(String[] args) {
PointFactory factory = new PointFactory();
Point point = factory.createPoint(5, 10); // Getting
the Point object
point.display(); // Outputs: Point coordinates: (5, 10)
}
Recursion in Java
Recursion is a programming technique where a method calls
itself to solve smaller instances of the same problem. It is
often used for tasks that can be defined in terms of
smaller subproblems, such as calculating factorials or
generating Fibonacci numbers.
Key Features of Recursion:
• Base Case: A condition under which the recursion
stops; it prevents infinite recursion.
• Recursive Case: The part of the function that includes
the recursive call.
Example
// Class to demonstrate recursion
class FactorialCalculator {
// Recursive method to calculate factorial
public int factorial(int n) {
if (n == 0 || n == 1) { // Base case
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
// Main class to test recursion
public class Main {
public static void main(String[] args) {
FactorialCalculator calculator = new
FactorialCalculator();
int number = 5;
int result = calculator.factorial(number); // Calling the
recursive method
System.out.println("Factorial of " + number + " is " +
result); // Outputs: Factorial of 5 is 120
}
15. Differentiate abstract base class and an interface.