0% found this document useful (0 votes)
13 views69 pages

Unit 2 Java Question Bank

The document contains a Java question bank with various types of questions, including very short answer type questions, short answer type questions, and explanations of key concepts such as inheritance, method overriding, and polymorphism. Each question is accompanied by its answer, providing insights into Java programming principles and practices. The content is structured to aid learners in understanding Java concepts through practical examples and definitions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views69 pages

Unit 2 Java Question Bank

The document contains a Java question bank with various types of questions, including very short answer type questions, short answer type questions, and explanations of key concepts such as inheritance, method overriding, and polymorphism. Each question is accompanied by its answer, providing insights into Java programming principles and practices. The content is structured to aid learners in understanding Java concepts through practical examples and definitions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Unit 2 Question bank

Very Short Answer Type Questions carrying 1 Marks

1. Output Finding: What is the output of the following code?

class A {

void show() {

[Link]("Class A");

class B extends A {

void show() {

[Link]("Class B");

public class Main {

public static void main(String[] args) {

A obj = new B();

[Link]();

Ans. Class B

2. What will be the output of the following code?

class Base {
int x = 10;

void display() {
[Link]("Base display");
}

}
class Derived extends Base {

int x = 20;

void display() {
[Link]("Derived display");
}

public class Test {

public static void main(String[] args) {

Base b = new Derived();

[Link](b.x);

[Link]();
}

Answer: 10, Derived display


3. What will be the output of the following code?
public class AccessTest {

private int num = 5;

public void display() {

[Link](num);
}

public static void main(String[] args) {

AccessTest obj = new AccessTest();

[Link]();
}
}

Answer: The output will be 5.

4. What will be the output of the following code?


public class AccessTest {

int num = 10;

void display() {
[Link](num);

public static void main(String[] args) {


AccessTest obj = new AccessTest();
[Link]();

Answer: The output will be 10.

5. What is the output of the following code?


class Parent {
void show() {

[Link]("Parent's show()");
}

class Child extends Parent {

void show() {
[Link]("Child's show()");
}

public class Test {

public static void main(String[] args) {

Parent p = new Child();


[Link]();

}
}

Answer: Child's show()


6. What is the output of the following code?
class A {

A() {

[Link]("A's constructor");
}

class B extends A {

B() {
[Link]("B's constructor");
}

public class Test {

public static void main(String[] args) {

B b = new B();
}

o Answer:
A's constructor

B's constructor

7. Output from Code

class Animal {

void sound() {
[Link]("Animal makes a sound");
}

class Cat extends Animal {


void sound() {

[Link]("Cat meows");

}
}

public class Test {

public static void main(String[] args) {

Animal a = new Cat();


[Link]();

}
Output: Cat meows

8. Output from Code


class Shape {

void draw() {
[Link]("Drawing Shape");

class Circle extends Shape {

void draw() {
[Link]("Drawing Circle");

class Square extends Shape {


void draw() {

[Link]("Drawing Square");

}
}

public class Test {

public static void main(String[] args) {


Shape s;

s = new Circle();
[Link]();

s = new Square();

[Link]();

}
}

Output:
mathematica
Copy code
Drawing Circle
Drawing Square

9. Find the error:

class Animal {
void eat() {

[Link]("This animal eats food.");


}

class Dog extends Animal {

void bark() {

[Link]("The dog barks.");


}

}
public class Test {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
[Link]();

[Link](); // Error

Answer: The method fly() is not defined in class Dog or its superclass Animal

10. Find the error: What is wrong with the following code snippet?

class MyClass {

private int myVar;


public void myMethod() {
[Link](myVar);
}

class AnotherClass {

public void anotherMethod() {


MyClass obj = new MyClass();
[Link]([Link]);

Answer: The error is in AnotherClass where it tries to access myVar which is


declared as private in MyClass. This results in a compilation error.

11. Find the error:


class Vehicle {

void start() {

[Link]("Vehicle is starting");

}
class Car extends Vehicle {

void start() {

[Link]("Car is starting");
}

public class TestVehicle {

public static void main(String[] args) {


Car c = new Car();

[Link]();
Vehicle v = new Car();

[Link]();

Vehicle v2 = new Vehicle();

[Link](); // Error
}
}

Answer: The method drive() is not defined in class Vehicle.

12. Find the Error


class Animal {

void sound() {

[Link]("Animal makes a sound");


}
}

class Dog extends Animal {


void Sound() { // Error here

[Link]("Dog barks");

}
}

public class Main {


public static void main(String[] args) {

Animal myDog = new Dog();

[Link]();
}
}

Error: The method in the Dog class should be void sound(), not void Sound().
Method names are case-sensitive.

13. Find Error


class Parent {
void display() {
[Link]("Parent class display method");

class Child extends Parent {

void display() { // Error here

[Link]("Child class display method");


}

public class Main {

public static void main(String[] args) {

Parent p = new Parent();

Child c = new Child();


[Link]();

[Link]();

p = c;
[Link](); // Error here
}

}
Error: There is no compile-time error. However, the output might not match the
expectations of someone unfamiliar with polymorphism. This demonstrates
polymorphism, where [Link]() will call the Child class's display method after p =
c.
14. Find the error:
package mypackage;

public class MyClass {

public void display() {

[Link]("Hello, World!");
}

import [Link];

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

[Link]();
}
}
Answer: The import statement should be placed at the beginning of the file, before the
class definitions.

15. Find the error:


interface MyInterface {
void display();

public class MyClass implements MyInterface {


void display() {

[Link]("Hello, World!");

public class Test {

public static void main(String[] args) {


MyClass obj = new MyClass();
[Link]();

Answer: The display method in MyClass should be declared as public to properly


implement the MyInterface.

16. What is the output?

interface MyInterface {

void display();
}
public class MyClass implements MyInterface {

public void display() {

[Link]("Hello, Interface!");
}

public class Test {


public static void main(String[] args) {

MyClass obj = new MyClass();

[Link]();
}
}

Answer: Hello, Interface!

17. What is the output?


package mypackage;

public interface MyInterface {

void display();

package mypackage;
public class MyClass implements MyInterface {

public void display() {

[Link]("Hello, World!");
}
}

import [Link];

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

[Link]();

}
}

Answer: Compilation error. The import statement should be at the beginning of the file.
18. What is method overloading?
Answer: Method Overloading: Occurs within the same class. Methods have the same
name but different parameters (number, type, or both). It is a compile-time polymorphism.

19. What is Method Overriding?


Answer: Method Overriding: Occurs in two classes that have an inheritance relationship.
The subclass provides a specific implementation of a method that is already defined in its
superclass. It is a runtime polymorphism.

20. Can a constructor be inherited in Java? Justify your answer.


Answer: No, constructors are not inherited in Java. Constructors are special methods used
to initialize objects and are not part of the object's inheritance. However, a subclass
constructor can call the superclass constructor using super().
Short Answer Type Questions carrying 5 Marks

1. What is inheritance in Java? How do you declare a class to be a subclass of


another class in Java?
Answer:Inheritance is a mechanism in Java where one class (subclass/child class)
inherits the properties and behaviors (fields and methods) of another class
(superclass/parent class). This allows for code reusability and the creation of a
hierarchical class structure.
Use the `extends` keyword. For example:
class SuperClass {

// Superclass code
}

class SubClass extends SuperClass {

// Subclass code

```
2. What is method overriding in Java? Give an example of method overriding.
What is dynamic method dispatch?
Answer: Method overriding occurs when a subclass provides a specific implementation
for a method that is already defined in its superclass. The method in the subclass should
have the same name, return type, and parameters as the method in the superclass.
class Animal {

void sound() {
[Link]("Animal makes a sound");

class Dog extends Animal {


void sound() {

[Link]("Dog barks");
}

Dynamic method dispatch is a mechanism by which a call to an overridden method is


resolved at runtime rather than compile-time. It allows a superclass reference to call
overridden methods in the subclass, enabling polymorphic behavior.

3. What is an abstract class in Java? Provide an example of an abstract class and a


subclass.
Answer: An abstract class in Java is a class that cannot be instantiated on its own and
is meant to be subclassed. It can have abstract methods (methods without a body) and
non-abstract methods (methods with a body).
abstract class Shape {

abstract void draw();

class Circle extends Shape {

void draw() {

[Link]("Drawing a circle");
}

4. Explain the concept of inheritance in Java and its benefits.


Answer: Inheritance in Java is a mechanism where one class acquires the properties
and behaviors (fields and methods) of another class. The class that inherits is called the
subclass (or derived class), and the class being inherited from is the superclass (or base
class).

Benefits:
a. Code Reusability: Inheritance promotes reusability of code, allowing the use
of existing code in new applications.
b. Method Overriding: It allows a subclass to provide a specific implementation
of a method that is already defined in its superclass.

c. Polymorphism: Inheritance supports polymorphism, which allows methods to


be used interchangeably among parent and child classes.

5. Define polymorphism and explain how it is implemented in Java.


Answer: Polymorphism in Java allows objects to be treated as instances of their parent
class rather than their actual class. This means a single action can be performed in
different ways.
Implementation:
1. Compile-Time Polymorphism: Achieved through method overloading.

2. Runtime Polymorphism: Achieved through method overriding.


class Animal {
void sound() {

[Link]("Animal makes a sound.");

class Dog extends Animal {

void sound() {

[Link]("Dog barks.");

public class TestPolymorphism {

public static void main(String[] args) {

Animal a;

a = new Dog();

[Link](); // Dog barks.

}
}

6. What is method overriding in Java? Provide an example. How does method


overloading differ from method overriding?
Answer: Method overriding occurs when a subclass provides a specific implementation
of a method that is already defined in its superclass. The method in the subclass must
have the same name, return type, and parameters as the method in the superclass.
class Vehicle {

void run() {

[Link]("Vehicle is running.");
}

class Bike extends Vehicle {


void run() {
[Link]("Bike is running.");

}
}

public class TestOverride {

public static void main(String[] args) {


Bike bike = new Bike();

[Link](); // Bike is running.

}
}
 Method Overloading: Occurs within the same class. Methods have the same name
but different parameters (number, type, or both). It is a compile-time polymorphism.

 Method Overriding: Occurs in two classes that have an inheritance relationship.


The subclass provides a specific implementation of a method that is already defined
in its superclass. It is a runtime polymorphism.

7. Can you override a static method in Java? Why or why not?


Answer: No, static methods cannot be overridden because they belong to the class, not
instances of the class. Method overriding is based on the instance of the class, whereas
static methods are resolved at compile time.
class Parent {

static void display() {

[Link]("Static method in Parent.");


}

class Child extends Parent {

static void display() {


[Link]("Static method in Child.");
}

public class TestStaticOverride {

public static void main(String[] args) {

[Link](); // Static method in Parent.


[Link](); // Static method in Child.

}
}
8. What is the `super` keyword used for in Java? Describe the concept of the super keyword

In Java with an example.


Answer:
The super keyword in Java is a reference variable used to refer to the immediate parent
class object. It can be used to access superclass methods, constructors, and variables.
class Animal {

String color = "white";

class Dog extends Animal {

String color = "black";

void printColor() {

[Link](color); // black

[Link]([Link]); // white

}
}

public class TestSuper {

public static void main(String[] args) {

Dog dog = new Dog();

[Link]();
}

9. What is an abstract class in Java, and how is it different from an interface?


Answer: An abstract class in Java is a class that cannot be instantiated and can have
abstract methods (methods without body) as well as concrete methods (methods with
body).
Differences:
1. Abstract Class: Can have both abstract and concrete methods. It can also have instance
variables.
2. Interface: Can only have abstract methods (before Java 8) and static or default methods
(from Java 8 onwards). It cannot have instance variables.

abstract class Shape {

abstract void draw();

class Circle extends Shape {

void draw() {

[Link]("Drawing Circle.");
}

public class TestAbstract {

public static void main(String[] args) {


Shape shape = new Circle();
[Link]();

10. Can a class extend more than one class in Java? Explain with reasons. How can
multiple inheritance be achieved in Java?
Answer: No, a class in Java cannot extend more than one class. This is known as single
inheritance. Java does not support multiple inheritance with classes to avoid complexity
and simplify the design, reducing the chances of ambiguity.
Multiple inheritance can be achieved in Java through interfaces. A class can implement
multiple interfaces, thus inheriting the abstract methods of all the interfaces.
interface Printable {

void print();

interface Showable {
void show();
}

class TestMultipleInheritance implements Printable, Showable {

public void print() {

[Link]("Printing.");
}

public void show() {

[Link]("Showing.");
}

public static void main(String[] args) {

TestMultipleInheritance obj = new TestMultipleInheritance();


[Link]();

[Link]();

11. Write a program demonstrating the concept of inheritance and polymorphism.


Answer:
class Employee {

void work() {
[Link]("Employee works.");
}

class Developer extends Employee {

void work() {
[Link]("Developer writes code.");
}
}
class Manager extends Employee {

void work() {
[Link]("Manager manages team.");
}

public class TestInheritancePolymorphism {

public static void main(String[] args) {

Employee emp1 = new Developer();

Employee emp2 = new Manager();

[Link](); // Developer writes code.


[Link](); // Manager manages team.

}
}

12. Explain the concept of constructor chaining in Java with an example.


Answer: Constructor chaining is the process of calling one constructor from another
constructor with respect to the current object. It can be done within the same class using
this() or from the base class using super().
class Base {

Base() {

[Link]("Base class constructor called.");


}

class Derived extends Base {

Derived() {

super(); // Calls the base class constructor

[Link]("Derived class constructor called.");

public class TestConstructorChaining {


public static void main(String[] args) {

Derived obj = new Derived();


}

13. Provide an example demonstrating method overloading.

Answer:
class MathOperation {

int add(int a, int b) {


return a + b;
}

int add(int a, int b, int c) {

return a + b + c;
}
}

public class TestOverloading {

public static void main(String[] args) {

MathOperation mo = new MathOperation();

[Link]([Link](5, 10)); // 15
[Link]([Link](5, 10, 15)); // 30
}

14. Explain covariance in Java with an example.


Answer: Covariance in Java allows a method to return a type that is a subclass of the
return type declared in the superclass method. This feature helps in overriding methods
with more specific return types.

class Animal {

Animal get() {

return this;
}

class Dog extends Animal {


Dog get() {
return this;
}

void bark() {

[Link]("Dog barks.");
}
}

public class TestCovariance {

public static void main(String[] args) {

new Dog().get().bark();

}
}

15. How do you prevent a class from being inherited in Java?


Answer: To prevent a class from being inherited, use the final keyword before the class
definition.

final class Car {

void drive() {
[Link]("Driving car.");
}

// The following will cause a compile-time error

// class SportsCar extends Car { }

public class TestFinalClass {

public static void main(String[] args) {

Car car = new Car();


[Link]();

}
16. What is the difference between super and this keywords in Java? What is the
significance of the final keyword in method definition?
Answer:
 super Keyword: Refers to the immediate parent class object and is used to access
parent class methods, variables, and constructors.
 this Keyword: Refers to the current object and is used to access current class methods,
variables, and constructors.

The final keyword in a method definition prevents the method from being overridden
in subclasses. This ensures that the behavior of the method remains consistent across
all classes.
class Parent {

final void show() {

[Link]("This is a final method.");

class Child extends Parent {

// This will cause a compile-time error // void show() { }

public class TestFinalMethod {

public static void main(String[] args) {


Child child = new Child();
[Link]();

17. Explain the concept of interface inheritance in Java with an example.


Answer: Interface inheritance in Java allows one interface to inherit another interface,
enabling a hierarchy of interfaces. A class implementing a child interface must
implement all methods from both the child and parent interfaces.
interface Printable {

void print();
}
interface Showable extends Printable {

void show();
}

class TestInterfaceInheritance implements Showable {

public void print() {


[Link]("Printing.");

public void show() {


[Link]("Showing.");

}
public static void main(String[] args) {

TestInterfaceInheritance obj = new TestInterfaceInheritance();

[Link]();
[Link]();
}

18. What is the role of the instanceof operator in inheritance and polymorphism?
Answer: The instanceof operator is used to test whether an object is an instance of a
specific class or interface. It helps in implementing polymorphic behavior by checking
the type of an object at runtime.
class Animal { }

class Dog extends Animal { }

public class TestInstanceof {

public static void main(String[] args) {


Animal animal = new Dog();

if (animal instanceof Dog) {


[Link]("animal is an instance of Dog.");
}
}

19. Write a Java program to demonstrate dynamic method dispatch.


Answer: Dynamic method dispatch is a mechanism by which a call to an overridden
method is resolved at runtime rather than at compile-time. This is an example of runtime
polymorphism.
class Animal {

void sound() {

[Link]("Animal makes a sound.");


}
}

class Dog extends Animal {

void sound() {

[Link]("Dog barks.");
}

class Cat extends Animal {

void sound() {

[Link]("Cat meows.");
}
}

public class TestDynamicDispatch {


public static void main(String[] args) {
Animal a;

a = new Dog();
[Link](); // Dog barks.

a = new Cat();

[Link](); // Cat meows.


}
}

20. What is a package in Java? How do you create a package in Java?


Answer: A package in Java is a namespace that organizes classes and
interfaces by functionality, making it easier to manage and avoid naming
conflicts. For example, [Link] contains utility classes like ArrayList and
HashMap.

To create a package, you use the package keyword at the top of your Java file.
For example:
package [Link];

public class MyClass {

// class content

21. What is the default package in Java? How do you import a package in Java?
Answer: If no package is specified, the class is placed in the default package, which
has no name. This is generally discouraged in large applications due to potential
naming conflicts.
Use the import keyword to bring a package or class into scope. For example:

Java code

import [Link];

import [Link].*;

22. What are the advantages of using packages? How do you access a class from a
different package?
Answer: Packages help in avoiding name conflicts, controlling access, providing
reusability, and making it easier to locate classes and interfaces.
To access a class from a different package, you need to import the package and
ensure the class is public. For example:
import [Link];

public class MainClass {

public static void main(String[] args) {

[Link]();

}
}

23. What is the [Link] package? Can you use a class from a package without
importing it?
Answer: The [Link] package is automatically imported and includes fundamental
classes like String, System, and Object.

Yes, by using the fully qualified name. For example:

public class MainClass {

public static void main(String[] args) {

[Link]();
}
}

24. What is a subpackage in Java? How do you compile and run a Java program
with packages?
Answer: A subpackage is a package within another package. For example,
[Link] can have a subpackage [Link].

Use javac to compile and specify the directory structure. For example:
sh
code

javac -d . com/example/[Link]

java [Link]

25. What is an interface in Java? How do you define an interface in Java?


Answer: An interface is a reference type in Java, similar to a class, that can contain
only constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructors.

Use the interface keyword. For example:

public interface MyInterface {

void myMethod();
}

26. How do you implement an interface in Java?


Answer: Use the implements keyword in a class. For example:

public class MyClass implements MyInterface {

public void myMethod() {


// implementation
}

27. Can an interface extend another interface?


Answer: Yes, an interface can extend multiple other interfaces. For example:
Java code

public interface MyInterface1 { /* ... */ }

public interface MyInterface2 { /* ... */ }

public interface MySubInterface extends MyInterface1, MyInterface2 { /* ... */ }

28. What is the difference between abstract classes and interfaces? What is a default
method in an interface?
Answer: An abstract class can have instance methods with implementations, fields,
and constructors, while an interface can only have static methods, default methods,
and method signatures. A class can extend only one abstract class but implement
multiple interfaces.
A default method is a method defined in an interface with the default keyword and an
implementation. For example:

public interface MyInterface {

default void myDefaultMethod() {


// default implementation

29. What is a marker interface? What is a functional interface in Java?


Answer: A marker interface is an interface with no methods or fields, used to indicate
a certain property or capability. For example, [Link].
A functional interface is an interface with exactly one abstract method. They can be
implemented using lambda expressions. For example:

public interface MyFunctionalInterface {

void myMethod();
}
30. How do you use a lambda expression with a functional interface?
Answer: By providing an implementation for the single abstract method. For
example:

Java code

MyFunctionalInterface myFunc = () -> [Link]("Hello");

[Link]();

31. Create a base class Animal with a method makeSound(). Create a derived class
Dog that overrides the makeSound() method.
Solution:
class Animal {

void makeSound() {

[Link]("Some sound...");
}
}

class Dog extends Animal {


void makeSound() {
[Link]("Bark");

}
}

public class Test {

public static void main(String[] args) {


Dog dog = new Dog();

[Link](); // Output: Bark


}
}

32. Explain the concept of polymorphism in Java. Illustrate runtime polymorphism


with an example involving a superclass Shape and subclasses Circle and
Rectangle.
Solution: Polymorphism in Java allows methods to do different things based on the object it
is acting upon. It can be achieved through method overriding (runtime polymorphism) and
method overloading (compile-time polymorphism). It enables one interface to be used for a
general class of actions.
class Shape {

void draw() {

[Link]("Drawing a shape");
}

class Circle extends Shape {

void draw() {

[Link]("Drawing a circle");
}

class Rectangle extends Shape {

void draw() {

[Link]("Drawing a rectangle");
}

public class Test {

public static void main(String[] args) {

Shape shape;

shape = new Circle();


[Link](); // Output: Drawing a circle

shape = new Rectangle();


[Link](); // Output: Drawing a rectangle
}

33. What are packages in Java, and how do you create and use them? Create a
package [Link] containing a class Square with a method area().
Answer: Packages in Java are used to group related classes, interfaces, and sub-packages.
They provide a modular structure to the code and help avoid name conflicts. You create a
package using the package keyword, and you can use classes from a package using the import
keyword.

// File: com/example/shapes/[Link]
package [Link];
public class Square {

private double side;


public Square(double side) {

[Link] = side;
}

public double area() {

return side * side;


}

// File: [Link]
import [Link];

public class Test {

public static void main(String[] args) {

Square square = new Square(5);


[Link]("Area: " + [Link]()); // Output: Area: 25.0

34. What is an interface in Java, and how does it differ from an abstract
class?Create an interface Flyable with a method fly(). Implement this interface in
a class Bird.
Solution: An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types. It cannot
contain instance fields. Interfaces are implemented by classes, providing a way to achieve
abstraction and multiple inheritance. Unlike abstract classes, interfaces cannot contain
method implementations (except default methods).

interface Flyable {

void fly();
}

class Bird implements Flyable {

public void fly() {

[Link]("Bird is flying");
}

public class Test {

public static void main(String[] args) {

Bird bird = new Bird();

[Link](); // Output: Bird is flying


}

35. How can an interface be used to achieve polymorphism? Create an interface


Playable with a method play(). Create two classes Guitar and Piano that implement
Playable and demonstrate polymorphism.
Solution: An interface can be used to achieve polymorphism by allowing multiple classes to
implement the same interface and provide different implementations of the interface methods.
This enables objects of different classes to be treated uniformly through the interface type.
interface Playable {

void play();
}

class Guitar implements Playable {


public void play() {

[Link]("Playing the guitar");

}
}

class Piano implements Playable {

public void play() {


[Link]("Playing the piano");

public class Test {

public static void main(String[] args) {


Playable instrument;

instrument = new Guitar();

[Link](); // Output: Playing the guitar

instrument = new Piano();

[Link](); // Output: Playing the piano

36. Explain how you can create a hierarchy of classes using inheritance and abstract
classes. Create an abstract class Employee with an abstract method calculateSalary().
Create two subclasses Manager and Developer that extend Employee and provide
specific implementations for the calculateSalary() method.
Solution: You can create a hierarchy of classes using inheritance by having a base abstract
class that defines common attributes and behaviors. Subclasses can extend the abstract class,
providing specific implementations for abstract methods and adding additional attributes and
behaviors as needed.
abstract class Employee {
abstract double calculateSalary();

class Manager extends Employee {


private double baseSalary;
private double bonus;

public Manager(double baseSalary, double bonus) {


[Link] = baseSalary;
[Link] = bonus;

double calculateSalary() {

return baseSalary + bonus;


}

class Developer extends Employee {

private double hourlyRate;


private int hoursWorked;

public Developer(double hourlyRate, int hoursWorked) {

[Link] = hourlyRate;
[Link] = hoursWorked;
}

double calculateSalary() {
return hourlyRate * hoursWorked;

}
}
public class Test {

public static void main(String[] args) {

Employee manager = new Manager(5000, 2000);


Employee developer = new Developer(50, 160);

[Link]("Manager's Salary: " + [Link]()); // Output:


Manager's Salary: 7000.0

[Link]("Developer's Salary: " + [Link]()); // Output:


Developer's Salary: 8000.0

37. Create two interfaces Swimmable and Runnable, each with a method swim() and
run() respectively. Create a class Triathlete that implements both interfaces.
Solution:
interface Swimmable {

void swim();

interface Runnable {

void run();
}

class Triathlete implements Swimmable, Runnable {


public void swim() {
[Link]("Triathlete is swimming");

public void run() {

[Link]("Triathlete is running");

}
}

public class Test {

public static void main(String[] args) {


Triathlete triathlete = new Triathlete();

[Link](); // Output: Triathlete is swimming


[Link](); // Output: Triathlete is running

}
}

38. Create a base class Person with a constructor that accepts a name. Create a
derived class Student that calls the base class constructor using super.
Solution:
class Person {
String name;

Person(String name) {

[Link] = name;
}
}

class Student extends Person {


int grade;

Student(String name, int grade) {

super(name);

[Link] = grade;
}

void display() {
[Link]("Name: " + name + ", Grade: " + grade);

public class Test {

public static void main(String[] args) {

Student student = new Student("John", 10);

[Link](); // Output: Name: John, Grade: 10


}

}
Long question Answer carrying 10 marks

1. What is constructor? Can an abstract class have a constructor? Provide an example.

Solution: a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

Yes, an abstract class can have a constructor. The constructor can be used to initialize fields
of the abstract class when instantiated through a subclass.

Example:
abstract class Animal {
String name;

Animal(String name) {

[Link] = name;

abstract void makeSound();

} class Dog extends Animal { Dog(String name) {


super(name);
}

void makeSound() {

[Link](name + " says Bark");


}

public class Test {

public static void main(String[] args) {


Dog dog = new Dog("Buddy");

[Link](); // Output: Buddy says Bark


}
}

2. Design a program that simulates an animal kingdom. There are different types of
animals (e.g., Lion, Elephant, Bird) that have different ways of making sounds and
moving. Create an abstract class Animal with abstract methods makeSound() and
move(). Create an interface Carnivore with a method hunt(). The Lion class should
implement Carnivore.
Solution:

1. Package Structure:
o animals: Contains the Animal class and its subclasses.
o behaviors: Contains the Carnivore interface.
2. Code:

// File: animals/[Link]
package animals;

public abstract class Animal {


public abstract void makeSound();

public abstract void move();

}
// File: animals/[Link]

package animals;
import [Link];

public class Lion extends Animal implements Carnivore {

public void makeSound() {


[Link]("Roar");
}

public void move() {

[Link]("The lion prowls");

}
public void hunt() {

[Link]("The lion hunts for food");


}

}
// File: animals/[Link]

package animals;

public class Elephant extends Animal {

public void makeSound() {


[Link]("Trumpet");

public void move() {

[Link]("The elephant walks slowly");

}
// File: animals/[Link]

package animals;

public class Bird extends Animal {

public void makeSound() {


[Link]("Chirp");

public void move() {


[Link]("The bird flies");

}
}

// File: behaviors/[Link]

package behaviors;

public interface Carnivore {

void hunt();
}

// File: [Link]
import animals.*;
import behaviors.*;

public class Main {

public static void main(String[] args) {


Animal lion = new Lion();
Animal elephant = new Elephant();

Animal bird = new Bird();

[Link]();

[Link]();

((Carnivore) lion).hunt();

[Link]();

[Link]();

[Link]();
[Link]();

}
}

3. Create a shape hierarchy with an abstract class Shape that has an abstract method
calculateArea(). Create a Drawable interface with a method draw(). Implement classes
Circle, Rectangle, and Square that inherit from Shape and implement Drawable.
Organize these classes into appropriate packages.

Solution:
1. Package Structure:
o shapes: Contains the Shape class and its subclasses.
o draw: Contains the Drawable interface.
2. Code:
// File: shapes/[Link]

package shapes;

public abstract class Shape {

public abstract double calculateArea();


}
// File: shapes/[Link]

package shapes;

import [Link];

public class Circle extends Shape implements Drawable {

private double radius;

public Circle(double radius) {

[Link] = radius;
}
public double calculateArea() {

return [Link] * radius * radius;

Override

public void draw() {


[Link]("Drawing a circle");

// File: shapes/[Link]

package shapes;

import [Link];
public class Rectangle extends Shape implements Drawable {

private double length;


private double width;

public Rectangle(double length, double width) {

[Link] = length;
[Link] = width;
}
public double calculateArea() {
return length * width;

public void draw() {

[Link]("Drawing a rectangle");

}
}

// File: shapes/[Link]

package shapes;

import [Link];

public class Square extends Shape implements Drawable {

private double side;

public Square(double side) {

[Link] = side;

}
public double calculateArea() {
return side * side;

public void draw() {

[Link]("Drawing a square");
}

// File: draw/[Link]
package draw;
public interface Drawable {

void draw();

// File: [Link]
import shapes.*;

import draw.*;

public class Main {

public static void main(String[] args) {

Shape circle = new Circle(5);

Shape rectangle = new Rectangle(4, 6);


Shape square = new Square(3);

[Link]("Circle area: " + [Link]());

((Drawable) circle).draw();

[Link]("Rectangle area: " + [Link]());


((Drawable) rectangle).draw();

[Link]("Square area: " + [Link]());

((Drawable) square).draw();

}
}

4. Create a vehicle system where there is an abstract class Vehicle with an abstract
method move(). Create an interface Fuelable with a method refuel(). Implement classes
Car, Bike, and Truck that inherit from Vehicle and implement Fuelable. Organize these
classes into appropriate packages.
Solution:
1. Package Structure:
o vehicles: Contains the Vehicle class and its subclasses.
o fuel: Contains the Fuelable interface.
2. Code:
// File: vehicles/[Link]
package vehicles;

public abstract class Vehicle {

public abstract void move();


}

// File: vehicles/[Link]

package vehicles;

import [Link];

public class Car extends Vehicle implements Fuelable {


public void move() {
[Link]("The car drives");

}
public void refuel() {

[Link]("Refueling the car");


}

// File: vehicles/[Link]

package vehicles;

import [Link];
public class Bike extends Vehicle implements Fuelable {

public void move() {

[Link]("The bike pedals");


}

public void refuel() {

[Link]("Refueling the bike");

}
}

// File: vehicles/[Link]

package vehicles;

import [Link];

public class Truck extends Vehicle implements Fuelable {

public void move() {


[Link]("The truck hauls");

public void refuel() {

[Link]("Refueling the truck");

}
}

// File: fuel/[Link]

package fuel;

public interface Fuelable {

void refuel();

// File: [Link]
import vehicles.*;

import fuel.*;

public class Main {

public static void main(String[] args) {

Vehicle car = new Car();

Vehicle bike = new Bike();

Vehicle truck = new Truck();

[Link]();

((Fuelable) car).refuel();

[Link]();

((Fuelable) bike).refuel();

[Link]();

((Fuelable) truck).refuel();

5. Explain how to extend interfaces in Java. Provide an example where you have a base
interface with some methods, then extend this interface in another interface, and finally
implement this extended interface in a class. Discuss how method overriding works in
this scenario.

Solution: In Java, an interface can extend another interface, similar to how a class extends
another class. When an interface extends another interface, it inherits all the abstract methods
of the parent interface. A class that implements the extended interface must provide
implementations for all the methods declared in the parent and child interfaces.

Here's an example:// Base Interface


interface Animal {
void eat();
void sleep();
}
// Extended Interface
interface Dog extends Animal {
void bark();
}

// Class implementing the extended interface


class Labrador implements Dog {

public void eat() {


[Link]("Labrador is eating.");
}

public void sleep() {


[Link]("Labrador is sleeping.");
}

public void bark() {


[Link]("Labrador is barking.");
}
}

public class TestInterface {


public static void main(String[] args) {
Labrador labrador = new Labrador();
[Link]();
[Link]();
[Link]();
}
}

In this example, Animal is the base interface with methods eat and sleep. The Dog interface
extends Animal and adds a new method bark. The Labrador class implements the Dog
interface, thus providing implementations for all the methods from both Animal and Dog
interfaces.

6. Describe the different types of visibility (access modifiers) available for classes and
packages in Java. Explain with an example how these modifiers affect the accessibility
of classes and their members within the same package and from different packages.
Solution: Java provides four access modifiers that determine the visibility of classes,
methods, and fields:

Public: Accessible from any other class.


Protected: Accessible within the same package and by subclasses in different
packages.
Default (no modifier): Accessible only within the same package.
Private: Accessible only within the same class.

Here's an example to illustrate these access modifiers:

File: com/example/base/[Link]

package [Link];

public class BaseClass {


public void publicMethod() {
[Link]("Public method in BaseClass");
}

protected void protectedMethod() {


[Link]("Protected method in BaseClass");
}

void defaultMethod() {
[Link]("Default method in BaseClass");
}

private void privateMethod() {


[Link]("Private method in BaseClass");
}

public void accessMethods() {


publicMethod();
protectedMethod();
defaultMethod();
privateMethod();
}
}

File: com/example/derived/[Link]
package [Link];

import [Link];

public class DerivedClass extends BaseClass {


public void accessMethods() {
publicMethod(); // Accessible
protectedMethod(); // Accessible
// defaultMethod(); // Not accessible
// privateMethod(); // Not accessible
}
}

File: com/example/[Link]

package [Link];

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
BaseClass base = new BaseClass();
[Link](); // Accessible
// [Link](); // Not accessible
// [Link](); // Not accessible
// [Link](); // Not accessible

DerivedClass derived = new DerivedClass();


[Link](); // Public and protected methods accessible
}
}

In this example:

o publicMethod is accessible from anywhere.


o protectedMethod is accessible within the same package and in subclasses.
o defaultMethod is accessible only within the same package.
o privateMethod is accessible only within the BaseClass.
7. What are packages in Java? Describe the significance of packages and how they help
in organizing classes. Create an example with multiple packages where classes interact
with each other, demonstrating the use of import statements.

Solution: Packages in Java are used to group related classes, interfaces, and sub-packages.
They help organize the codebase, manage access control, and avoid name conflicts.

Here's an example with multiple packages:

File: com/example/animals/[Link]

package [Link];

public class Animal {


public void sound() {
[Link]("Animal makes a sound.");
}
}

File: com/example/animals/[Link]

jpackage [Link];

public class Dog extends Animal {


public void sound() {
[Link]("Dog barks.");
}
}

File: com/example/zoo/[Link]

package [Link];

import [Link];
import [Link];

public class Zoo {


public static void main(String[] args) {
Animal animal = new Animal();
[Link]();

Dog dog = new Dog();


[Link]();
}
}

In this example:

o The [Link] package contains the Animal and Dog classes.


o The [Link] package contains the Zoo class, which uses the Animal
and Dog classes.
o The import statements in [Link] allow it to use classes from the
[Link] package.

8. Discuss how visibility and access control work in Java with respect to packages.
Provide an example where classes in different packages access each other's public,
protected, default, and private members. Explain the results and why they occur.

Solution: In Java, visibility and access control with respect to packages are managed using
access modifiers (public, protected, default, and private). Here's an example demonstrating
access control:

File: com/example/package1/[Link]

package [Link].package1;

public class ClassA {


public void publicMethod() {
[Link]("Public method in ClassA");
}

protected void protectedMethod() {


[Link]("Protected method in ClassA");
}

void defaultMethod() {
[Link]("Default method in ClassA");
}

private void privateMethod() {


[Link]("Private method in ClassA");
}

public void accessMethods() {


publicMethod();
protectedMethod();
defaultMethod();
privateMethod();
}
}

File: com/example/package2/[Link]

package [Link].package2;

import [Link];

public class ClassB extends ClassA {


public void accessMethods() {
publicMethod(); // Accessible
protectedMethod(); // Accessible
// defaultMethod(); // Not accessible
// privateMethod(); // Not accessible
}
}

File: com/example/[Link]

package [Link];

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
ClassA classA = new ClassA();
[Link](); // Accessible
// [Link](); // Not accessible
// [Link](); // Not accessible
// [Link](); // Not accessible

ClassB classB = new ClassB();


[Link](); // Public and protected methods accessible
}
}

In this example:
o publicMethod is accessible from anywhere.
o protectedMethod is accessible within the same package and in subclasses.
o defaultMethod is accessible only within the same package.
o privateMethod is accessible only within the ClassA.

When ClassB in [Link].package2 extends ClassA in [Link].package1, it can


access the public and protected methods of ClassA, but not the default or private methods. In
the Main class, instances of ClassA and ClassB can access public methods, but protected
methods are only accessible within subclasses.

9. What is an abstract class in Java, and how does it differ from a regular class? Create
an abstract class Vehicle with an abstract method move(). Implement this method in a
subclass Car.
Answer: An abstract class in Java is a class that cannot be instantiated on its own and may
contain abstract methods (methods without a body). It serves as a blueprint for other classes.
Unlike regular classes, abstract classes can have both abstract and concrete methods.
abstract class Vehicle {
abstract void move();

class Car extends Vehicle {


void move() {
[Link]("Car is moving");

public class Test {


public static void main(String[] args) {
Car car = new Car();

[Link](); // Output: Car is moving

}
10. What are access specifiers in Java? Explain the different types of access
specifiers available and their significance. Provide examples to illustrate how each
access specifier controls access to class members.

Solution: Access specifiers in Java determine the visibility and accessibility of classes,
methods, and variables. Java provides four types of access specifiers:

Public: The member is accessible from any other class.


Protected: The member is accessible within the same package and by subclasses in different
packages.
Default (no modifier): The member is accessible only within the same package.
Private: The member is accessible only within the same class.

Here’s an example illustrating each access specifier:

public class AccessSpecifiersExample {


public int publicVar = 1;
protected int protectedVar = 2;
int defaultVar = 3;
private int privateVar = 4;
public void publicMethod() {
[Link]("Public method");
}

protected void protectedMethod() {


[Link]("Protected method");
}

void defaultMethod() {
[Link]("Default method");
}

private void privateMethod() {


[Link]("Private method");
}

public void display() {


[Link]("publicVar: " + publicVar);
[Link]("protectedVar: " + protectedVar);
[Link]("defaultVar: " + defaultVar);
[Link]("privateVar: " + privateVar);

publicMethod();
protectedMethod();
defaultMethod();
privateMethod();
}
}

class TestAccess {
public static void main(String[] args) {
AccessSpecifiersExample example = new AccessSpecifiersExample();

// Accessing public member


[Link]("Public var: " + [Link]);
[Link]();

// Accessing protected member


[Link]("Protected var: " + [Link]);
[Link]();

// Accessing default member


[Link]("Default var: " + [Link]);
[Link]();

// Accessing private member (not allowed, will cause compile-time error)


// [Link]("Private var: " + [Link]);
// [Link]();

[Link]();
}
}

In this example:

o publicVar and publicMethod are accessible from any class.


o protectedVar and protectedMethod are accessible within the same package and
subclasses.
o defaultVar and defaultMethod are accessible only within the same package.
o privateVar and privateMethod are accessible only within the
AccessSpecifiersExample class.

11. Explain the public access specifier in Java. How does it affect the accessibility of
classes, methods, and variables? Provide an example where a class, its methods, and its
variables are declared as public.
Solution: The public access specifier allows the class, method, or variable to be accessible
from any other class, regardless of the package. It ensures the widest possible visibility.

Here's an example:

// File: com/example/publicaccess/[Link]
package [Link];

public class PublicClass {


public int publicVar = 10;
public void publicMethod() {
[Link]("Public method in PublicClass");
}
}

// File: com/example/main/[Link]
package [Link];

import [Link];

public class MainClass {


public static void main(String[] args) {
PublicClass publicClass = new PublicClass();
[Link]("Public variable: " + [Link]);
[Link]();
}
}

In this example:

o PublicClass is declared as public, so it can be accessed from MainClass in a


different package.
o publicVar and publicMethod are also declared as public, making them
accessible from any class.

12. Describe the protected access specifier in Java. How does it control the accessibility
of class members? Provide an example showing how protected members can be accessed
within the same package and from a subclass in a different package.

Solution: The protected access specifier allows the member to be accessible within the same
package and by subclasses in different packages. It provides a balance between package-level
and subclass-level access.

Here's an example:
// File: com/example/base/[Link]
package [Link];

public class BaseClass {


protected int protectedVar = 20;
protected void protectedMethod() {
[Link]("Protected method in BaseClass");
}
}

// File: com/example/sub/[Link]
package [Link];

import [Link];

public class SubClass extends BaseClass {


public void display() {
[Link]("Protected variable: " + protectedVar);
protectedMethod();
}
}

// File: com/example/main/[Link]
package [Link];

import [Link];

public class MainClass {


public static void main(String[] args) {
SubClass subClass = new SubClass();
[Link]();
}
}

In this example:

o protectedVar and protectedMethod in BaseClass are accessible in SubClass


which is in a different package.
o The MainClass demonstrates that the protected members are accessible
through inheritance.
13. What is the default (package-private) access specifier in Java? How does it affect the
visibility of class members? Provide an example where default access specifier is used to
restrict access to within the same package.

Solution: The default (package-private) access specifier, when no access modifier is


specified, restricts the accessibility to within the same package. It ensures that the members
are not accessible from classes in different packages.

Here's an example:

// File: com/example/package1/[Link]
package [Link].package1;

class DefaultClass {
int defaultVar = 30;

void defaultMethod() {
[Link]("Default method in DefaultClass");
}
}

// File: com/example/package1/[Link]
package [Link].package1;

public class TestDefaultAccess {


public static void main(String[] args) {
DefaultClass defaultClass = new DefaultClass();
[Link]("Default variable: " + [Link]);
[Link]();
}
}

// File: com/example/package2/[Link]
package [Link].package2;

import [Link];

public class TestDefaultAccessInDifferentPackage {


public static void main(String[] args) {
// DefaultClass defaultClass = new DefaultClass(); // Not accessible
// [Link]("Default variable: " + [Link]); // Not accessible
// [Link](); // Not accessible
}
}

In this example:

o DefaultClass, defaultVar, and defaultMethod are accessible within the same


package ([Link].package1).
o TestDefaultAccessInDifferentPackage cannot access DefaultClass or its
members because they have default access.

14. Explain the private access specifier in Java. How does it control the accessibility of
class members? Provide an example to show how private members are restricted to the
defining class.

Solution: The private access specifier restricts the accessibility of class members to within
the defining class only. It is the most restrictive access level.

Here's an example:

public class PrivateClass {


private int privateVar = 40;

private void privateMethod() {


[Link]("Private method in PrivateClass");
}

public void display() {


[Link]("Private variable: " + privateVar);
privateMethod();
}
}

public class TestPrivateAccess {


public static void main(String[] args) {
PrivateClass privateClass = new PrivateClass();
// [Link]("Private variable: " + [Link]); // Not accessible
// [Link](); // Not accessible
[Link]();
}
}

In this example:
o privateVar and privateMethod are accessible only within the PrivateClass.
o The display method in PrivateClass provides controlled access to private
members.

15. Can a class in Java have members with different access specifiers? Provide an
example demonstrating a class with public, protected, default, and private members.
Explain how each member can be accessed from within the class, from the same
package, from a subclass, and from a different package.

Solution: Yes, a class in Java can have members with different access specifiers. Here’s an
example demonstrating this:

package [Link];

public class CombinedAccessSpecifiers {


public int publicVar = 1;
protected int protectedVar = 2;
int defaultVar = 3;
private int privateVar = 4;
public void publicMethod() {
[Link]("Public method");
}

protected void protectedMethod() {


[Link]("Protected method");
}

void defaultMethod() {
[Link]("Default method");
}

private void privateMethod() {


[Link]("Private method");
}

public void display() {


[Link]("publicVar: " + publicVar);
[Link]("protectedVar: " + protectedVar);
[Link]("defaultVar: " + defaultVar);
[Link]("privateVar: " + privateVar);

publicMethod();
protectedMethod();
defaultMethod();
privateMethod();
}
}

package [Link];

public class TestCombinedAccess {


public static void main(String[] args) {
CombinedAccessSpecifiers example = new CombinedAccessSpecifiers();

// Accessing public member


[Link]("Public var: " + [Link]);
[Link]();

// Accessing protected member


[Link]("Protected var: " + [Link]);
[Link]();

// Accessing default member


[Link]("Default var: " + [Link]);
[Link]();

// Accessing private member (not allowed, will cause compile-time error)


// [Link]("Private var: " + [Link]);
// [Link]();

[Link]();
}
}

In this example:

o publicVar and publicMethod are accessible from any class.


o protectedVar and protectedMethod are accessible within the same package and
by subclasses.
o defaultVar and defaultMethod are accessible only within the same package.
o privateVar and privateMethod are accessible only within the
CombinedAccessSpecifiers class.
16. Discuss the practical usage of different access specifiers in a real-world application.
Provide an example where a class uses all access specifiers to encapsulate data and
provide controlled access. Explain the design choices made for each access level.

Solution: In a real-world application, access specifiers are used to encapsulate data and
provide controlled access to class members, ensuring data integrity and hiding
implementation details. Here's an example:

package [Link];

public class BankAccount {


// Private variable to store the account balance
private double balance;

// Protected variable accessible within the package and subclasses


protected String accountNumber;

// Default variable accessible within the package


String accountHolderName;

// Public method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount);
} else {
[Link]("Invalid deposit amount.");
}
}

// Public method to withdraw money


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Invalid or insufficient funds.");
}
}

// Public method to display account details


public void displayAccountDetails() {
[Link]("Account Holder: " + accountHolderName);
[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + balance);
}

// Private method to calculate interest


private double calculateInterest(double rate) {
return balance * rate / 100;
}

// Public method to add interest to the balance


public void addInterest(double rate) {
double interest = calculateInterest(rate);
balance += interest;
[Link]("Interest added: " + interest);
}
}

// Subclass in the same package


package [Link];

public class SavingsAccount extends BankAccount {


public void setAccountNumber(String accountNumber) {
[Link] = accountNumber;
}
}

// Main class to test the BankAccount class


package [Link];

import [Link];
import [Link];

public class MainClass {


public static void main(String[] args) {
BankAccount account = new BankAccount();
[Link] = "John Doe"; // Default access
// [Link] = "123456"; // Protected access not allowed here
[Link](1000);
[Link](500);
[Link](5);
[Link]();

SavingsAccount savings = new SavingsAccount();


[Link]("123456");
[Link](2000);
[Link](1000);
[Link](3);
[Link]();
}
}

In this example:

o balance is private to encapsulate and protect the account balance from direct
modification.
o accountNumber is protected to allow subclasses to access and modify it.
o accountHolderName has default access, as it is relevant only within the
package.
o Public methods deposit, withdraw, displayAccountDetails, and addInterest
provide controlled access to the class's functionality.
o The private method calculateInterest encapsulates the logic for interest
calculation, hiding it from external access.

17. What is inheritance. Explain each type of inheritance using program.

Answer: In Java, inheritance is a key feature of object-oriented programming that


allows one class to inherit fields and methods from another class. Java supports
several types of inheritance, but there are some constraints compared to other
languages due to Java's single inheritance model for classes.

Here's an overview of inheritance and its types in Java:

1. Single Inheritance

In single inheritance, a class (child class) inherits from one and only one base class
(parent class). This is the most straightforward form of inheritance in Java.
Example:// Base class
class Animal { void eat() {
[Link]("This animal eats food.");
}
}

// Derived class
class Dog extends Animal {
void bark() {
[Link]("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Inherited method
[Link](); // Method of Dog class
}
}

2. Multiple Inheritance (through Interfaces)

Java does not support multiple inheritance with classes due to the complexity it introduces,
such as the "Diamond Problem." However, Java allows a class to implement multiple
interfaces, thus providing a form of multiple inheritance.

Example:

interface Animal {
void eat();
}

interface Pet {
void play();
}

class Dog implements Animal, Pet {


public void eat() {
[Link]("The dog eats.");
}

public void play() {


[Link]("The dog plays.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
[Link]();
}
}

3. Multilevel Inheritance

In multilevel inheritance, a class inherits from another class, which itself inherits from
another class. This creates a chain of inheritance.

Example:

// Base class
class Animal {
void eat() {
[Link]("This animal eats food.");
}
}

// Intermediate class
class Mammal extends Animal {
void breathe() {
[Link]("This mammal breathes air.");
}
}

// Derived class
class Dog extends Mammal {
void bark() {
[Link]("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Inherited from Animal
[Link](); // Inherited from Mammal
[Link](); // Method of Dog
}
}

4. Hierarchical Inheritance

In hierarchical inheritance, a single base class is inherited by multiple derived classes.


Example:

// Base class
class Animal {
void eat() {
[Link]("This animal eats food.");
}
}

// Derived classes
class Dog extends Animal {
void bark() {
[Link]("The dog barks.");
}
}

class Cat extends Animal {


void meow() {
[Link]("The cat meows.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
Cat myCat = new Cat();

[Link](); // Inherited from Animal


[Link]();

[Link](); // Inherited from Animal


[Link]();
}
}

5. Hybrid Inheritance

Java does not support hybrid inheritance through classes due to the complexity and potential
for ambiguity. However, hybrid inheritance is achievable using a combination of interfaces.
In this setup, a class can implement multiple interfaces and extend another class, effectively
creating a hybrid inheritance scenario.

Example:
interface Animal {
void eat();
}

interface Pet {
void play();
}

class Mammal {
void breathe() {
[Link]("This mammal breathes air.");
}
}

class Dog extends Mammal implements Animal, Pet {


public void eat() {
[Link]("The dog eats.");
}

public void play() {


[Link]("The dog plays.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
[Link]();
[Link]();
}
}
Key Points:

o Java supports only single inheritance with classes but allows multiple
inheritance through interfaces.
o Java uses the extends keyword for class inheritance and the implements
keyword for interfaces.
o Java provides flexibility in inheritance through its use of interfaces,
allowing multiple inheritance-like behavior.
Understanding these inheritance types helps in designing class hierarchies and
leveraging the full power of Java's object-oriented features.

Common questions

Powered by AI

Encapsulation in Java can be achieved by using access specifiers to control access to the fields and methods of a class. By declaring class member variables private, their access is restricted to within the class. Public methods (getters and setters) provide controlled access to these variables . For instance, in a 'BankAccount' class, the balance should be a private variable, while methods like deposit and withdraw are public, allowing users to interact with the account securely . This control ensures data integrity and abstracts the internal workings of a class from outside interference .

Constructors cannot be inherited in Java because they are not part of an object's inheritance. Constructors are special methods used for object initialization and are specific to the class to which they belong. However, a subclass can call a superclass constructor using the super() keyword directly, but this does not imply inheritance . For example, in a class hierarchy where a subclass Dog extends Animal, the Dog constructor can invoke the Animal constructor, but neither the Dog class inherits it, nor can it execute the superclass constructor directly .

An abstract class in Java can have both abstract methods (methods without a body) and concrete methods (with a body), whereas an interface traditionally could only declare method signatures with no implementation, but from Java 8 onwards, it can also include default and static methods . Abstract classes can have instance variables while interfaces cannot . These differences impact Java program design in that abstract classes are best used for creating base classes for a group of related classes with shared behavior, while interfaces allow for a class to specify a contract of methods it must implement, promoting flexibility and decoupling .

Access specifiers in Java control the visibility and accessibility of classes, methods, and variables . The public specifier allows access from any class . Protected access is within the same package and by subclasses in different packages . Default (package-private) accessibility is limited to the package, without any explicit modifier . Private access restricts visibility to within the defining class only . This control allows developers to encapsulate data, expose functionality, and prevent unauthorized access .

Runtime polymorphism in Java allows methods to be resolved at runtime rather than compile time, enabling dynamic method invocation and making the system more flexible and extensible . Compile-time polymorphism, such as method overloading, resolves methods at compile time based on method signatures . An example of runtime polymorphism is method overriding, where a subclass method is called at runtime using a superclass reference. For example, a reference of type 'Shape' may point to an instance of 'Circle', and invoking 'draw()' will call the 'Circle' class's overridden method .

While Java does not support multiple inheritance for classes to avoid complexity and ambiguity, it does allow a class to implement multiple interfaces, which achieves multiple inheritance at the interface level . This enables Java classes to inherit abstract methods from multiple sources, allowing for a more flexible and modular design. For example, a class can implement both Printable and Showable interfaces to inherit methods from both without the complications linked to class inheritance .

Marker interfaces in Java are interfaces with no methods or fields, such as 'Serializable', used to indicate a certain capability or property at runtime without defining any methods . Functional interfaces, in contrast, have exactly one abstract method and can be implemented using lambda expressions, enabling concise instance creation of functional objects. They are commonly used in scenarios requiring single-function abstractions like Runnable or Comparator, supporting functional programming paradigms . Marker interfaces are used more as a mechanism to tag or mark objects in a way that the code can recognize certain properties dynamically .

Method overloading occurs within the same class and involves methods with the same name but different parameters (number, type, or both). It is a compile-time polymorphism . Method overriding, on the other hand, occurs in two classes with an inheritance relationship, where a subclass provides a specific implementation for a method already defined in its superclass, thus enabling runtime polymorphism . While method overloading enables flexibility and customization by allowing multiple method signatures, overriding provides a mechanism for dynamic method dispatch, which is key to implementing polymorphic behaviors in inheritance hierarchies .

Java's package system helps in organizing related classes and interfaces into namespaces, which makes it easier to manage large software projects and avoid name conflicts . Packages group classes in a directory structure, enhancing modularity and code reusability. To create a package, define it at the beginning of a Java file using the package keyword, e.g., 'package com.example.shapes;' for a class 'Square'. To use the package, other classes can import it using 'import com.example.shapes.Square;' .

The 'super' keyword in Java is crucial for implementing certain object-oriented principles like inheritance and encapsulation. It allows a subclass to access methods or variables from its superclass, which is particularly useful when a method in the subclass overrides one in the superclass, and the functionality of the superclass method is still desired . This supports the inheritance principle by enabling subclasses to extend and modify superclass behavior while still maintaining access to superclass methods and fields, thus adhering to encapsulation .

You might also like