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

Java Practical Manual Exe 2 Ans

JAVA PRACTICAL MANUAL EXE 2 ANS

Uploaded by

solomon isaac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

Java Practical Manual Exe 2 Ans

JAVA PRACTICAL MANUAL EXE 2 ANS

Uploaded by

solomon isaac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

LABORATORY EXERCISE 1

ANSWERS
1. In Java, OPP (Object-Oriented Programming) is a programming paradigm that
focuses on organizing code around objects, which are instances of classes. OPP
promotes the concepts of encapsulation, inheritance, polymorphism, and abstraction
to structure code and facilitate modular, reusable, and maintainable software
development.

2. Four main features of Object-Oriented Programming are:


1. Encapsulation: Encapsulation is the practice of bundling data (attributes) and methods
(functions) together into a single unit called a class. It provides data hiding by
controlling access to the internal state of an object. Encapsulation helps in
maintaining the integrity and security of data and prevents direct modification from
external code.
2. Inheritance: Inheritance allows the creation of a new class (subclass) by deriving
properties and behaviors from an existing class (superclass). The subclass inherits the
attributes and methods of the superclass and can add new features or override existing
ones. Inheritance promotes code reuse, enables hierarchical relationships, and
supports the concept of "is-a" relationship between classes.
3. Polymorphism: Polymorphism refers to the ability of an object to take on many forms.
It allows a subclass to provide a different implementation of a method that is already
defined in its superclass through method overriding. Polymorphism enables dynamic
binding, where the appropriate method implementation is determined at runtime based
on the actual object type. It supports code extensibility and flexibility.
4. Abstraction: Abstraction focuses on capturing the essential features and behavior of an
object or system while hiding unnecessary details. It provides a simplified
representation of complex systems by creating abstract classes and interfaces.
Abstract classes define common attributes and methods that can be inherited by
subclasses, while interfaces define a contract of methods that classes must implement.
Abstraction helps in managing complexity, modularity, and code maintainability.

3. Understanding of Classes:
In Java, a class is a blueprint or template for creating objects. It defines the attributes
(data members) and behaviors (methods) that objects of that class will have. A class
serves as a fundamental building block of object-oriented programming. It
encapsulates data and provides methods to interact with that data. It represents a
category or type of objects and defines the shared characteristics and functionalities
among them.
A class can have constructors to initialize objects, attributes to store data, and methods to
perform actions or provide functionality. Objects are created from classes using the
'new' keyword, and each object has its own set of attribute values and can invoke the
methods defined in its class. Classes facilitate code reuse, modularization, and the
organization of related data and behaviors in a structured manner.

4. An Object:
An object is an instance of a class. It represents a specific entity or item created from a
class blueprint. Objects have state (attributes) and behavior (methods) defined by the
class. Each object is a separate entity with its own memory allocation, and changes
made to one object do not affect other objects of the same class.

Objects are created using the 'new' keyword followed by the constructor of the class.
They can be used to store data, perform actions, or interact with other objects. Objects
provide a way to model real-world entities, encapsulate data and behavior, and
facilitate modular and reusable code design. They are the primary building blocks of
object-oriented programming.

LABORATORY EXERCISE 2
ANSWERS
QUESTION 1
1. INHERITANCE
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one
class to inherit properties and behaviors from another class. Inheritance establishes a "is-a"
relationship between classes, where the subclass (derived class) inherits characteristics from
the superclass (base class). The subclass can extend or specialize the functionality of the
superclass by adding new methods or overriding existing ones.

QUESTION 2
Here's an example program in Java that demonstrates the concept of inheritance:
```java
// Superclass
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println(name + " is barking.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Animal animal = new Animal("Generic Animal");
animal.eat();
animal.sleep();

System.out.println();

Dog dog = new Dog("Buddy");


dog.eat();
dog.sleep();
dog.bark();
}
}
```

In this example, we have a superclass called `Animal` and a subclass called `Dog`. The
`Animal` class has a `name` attribute and two methods, `eat()` and `sleep()`, which are
inherited by the `Dog` class. The `Dog` class adds a new method called `bark()`.

In the `main` method, we create an instance of the `Animal` class and call its `eat()` and
`sleep()` methods. Then, we create an instance of the `Dog` class and call all three methods:
`eat()`, `sleep()`, and `bark()`. The output will show the respective actions performed by the
animal and the dog.

This example demonstrates how the `Dog` class inherits the attributes and methods from the
`Animal` class, allowing it to access and utilize them. Inheritance promotes code reuse,
abstraction, and extensibility by allowing classes to inherit and extend the functionality of
existing classes.

LABORATORY EXERCISE 3
ANSWERS
2. Polymorphism is a key concept in object-oriented programming that allows objects of
different classes to be treated as objects of a common superclass. It enables a single
interface to be used to represent multiple types of objects. Polymorphism is achieved
through method overriding and method overloading.

3. Here's an example program to demonstrate the concept of polymorphism:


```java
// Superclass
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}

// Subclass 1
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks.");
}
}

// Subclass 2
class Cat extends Animal {
public void makeSound() {
System.out.println("The cat meows.");
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Animal animal1 = new Dog(); // Polymorphic behavior
Animal animal2 = new Cat(); // Polymorphic behavior

animal1.makeSound(); // Output: The dog barks.


animal2.makeSound(); // Output: The cat meows.
}
}
```

In this program, we have a superclass `Animal` with a method `makeSound()`. The `Dog` and
`Cat` classes are subclasses of `Animal` and override the `makeSound()` method with their
specific implementations.

In the `main()` method, we create objects of `Dog` and `Cat` classes but assign them to
variables of type `Animal`. This demonstrates polymorphic behavior, as the objects of the
subclasses are treated as objects of the superclass. When we call the `makeSound()` method
on these objects, the overridden methods in the respective subclasses are invoked based on
the actual object type.
The program shows how polymorphism allows different objects to respond differently to the
same method call, based on their specific implementations.
LABORATORY EXERCISE 4
ANSWERS
1. Abstraction is a fundamental principle in object-oriented programming that focuses on
representing the essential features and behavior of an object or system while hiding
unnecessary details. It provides a simplified and generalized view of complex systems.
2. Here's an example program to demonstrate the concept of abstraction using abstract
classes and interfaces:

```java
// Abstract class
abstract class Shape {
// Abstract method
public abstract void draw();

// Concrete method
public void display() {
System.out.println("Displaying the shape.");
}
}

// Concrete subclass
class Circle extends Shape {
// Implementing the abstract method
public void draw() {
System.out.println("Drawing a circle.");
}
}

// Interface
interface Drawable {
void draw();
}

// Concrete class implementing an interface


class Rectangle implements Drawable {
public void draw() {
System.out.println("Drawing a rectangle.");
}
}

public class AbstractionDemo {


public static void main(String[] args) {
Shape shape = new Circle(); // Polymorphic behavior
shape.draw(); // Output: Drawing a circle
shape.display(); // Output: Displaying the shape

Drawable drawable = new Rectangle(); // Polymorphic behavior


drawable.draw(); // Output: Drawing a rectangle
}
}
```

In this program, we have an abstract class `Shape` that defines an abstract method `draw()`
and a concrete method `display()`. The `Circle` class is a concrete subclass of `Shape` that
provides an implementation for the `draw()` method. The `Rectangle` class is a concrete class
that implements the `Drawable` interface, which specifies the `draw()` method.

In the `main()` method, we create objects of the `Circle` and `Rectangle` classes, but assign
them to variables of types `Shape` and `Drawable` respectively. This demonstrates
polymorphic behavior and abstraction, as we interact with the objects using the abstract class
and interface. We can call the `draw()` method on these objects, and the appropriate
implementations are invoked based on the actual object types.
The program illustrates how abstraction allows us to define common behavior in abstract
classes and interfaces, hiding the specific details of implementation. It provides a simplified
and generalized view of objects and promotes code modularity and flexibility.

LABORATORY EXERCISE 5
ANSWERS
1. Overriding is a feature in object-oriented programming that allows a subclass to
provide a different implementation of a method that is already defined in its
superclass. It is used to modify the behavior of inherited methods to suit the specific
needs of the subclass. The overridden method in the subclass must have the same
name, return type, and parameters as the method in the superclass.

2. Here's an example program to demonstrate the concept of method overriding:

```java
// Superclass
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}

// Subclass
class Dog extends Animal {
// Overriding the makeSound() method
public void makeSound() {
System.out.println("The dog barks.");
}
}

public class OverridingDemo {


public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: The animal makes a sound.

Dog dog = new Dog();


dog.makeSound(); // Output: The dog barks.

Animal animal2 = new Dog(); // Polymorphic behavior


animal2.makeSound(); // Output: The dog barks.
}
}
```

LABORATORY EXERCISE 6
ANSWERS
1. Encapsulation is a fundamental principle in object-oriented programming that
combines data (attributes) and methods (functions) into a single unit called a class. It
provides data hiding and abstraction by controlling the access to the internal state of
an object. Encapsulation helps in maintaining the integrity and security of data by
preventing direct modification from external code.
In Java, encapsulation is achieved by declaring class variables as private and providing public
getter and setter methods to access and modify the data. This way, the internal state of the
object remains hidden, and interactions with the object are controlled through defined
methods.

2. Here's an example program to demonstrate the concept of encapsulation:

```java
// Encapsulated class
class Person {
private String name;
private int age;

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for age


public int getAge() {
return age;
}

// Setter method for age


public void setAge(int age) {
if (age >= 0) {
this.age = age;
} else {
System.out.println("Invalid age.");
}
}
}

public class EncapsulationDemo {


public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(30);
System.out.println("Name: " + person.getName()); // Output: John
System.out.println("Age: " + person.getAge()); // Output: 30

person.setAge(-5); // Invalid age.


System.out.println("Age: " + person.getAge()); // Output: 30
}
}

LABORATORY EXERCISE 7
ANSWERS
1. ATTRIBUTES
In object-oriented programming (OOP), attributes are the variables or data members
associated with a class. They represent the state or characteristics of an object. Attributes
store information about the object's properties and can have different data types, such as
integers, strings, booleans, etc. They define the data that an object can hold.

2. Here's an example program to demonstrate the concept of attributes:


// Class with attributes
class Student {
String name;
int age;
String major;
}
public class AttributesDemo {
public static void main(String[] args) {
// Creating objects of the Student class
Student student1 = new Student();
student1.name = "John";
student1.age = 20;
student1.major = "Computer Science";

Student student2 = new Student();


student2.name = "Jane";
student2.age = 19;
student2.major = "Physics";

// Accessing and printing the attributes of objects


System.out.println("Student 1:");
System.out.println("Name: " + student1.name);
System.out.println("Age: " + student1.age);
System.out.println("Major: " + student1.major);
System.out.println();
System.out.println("Student 2:");
System.out.println("Name: " + student2.name);
System.out.println("Age: " + student2.age);
System.out.println("Major: " + student2.major);
}
}
LABORATORY EXERCISE 8
ANSWERS
1. METHOD
In object-oriented programming (OOP), a method is a function associated with a class or an
object. Methods define the behavior or actions that an object can perform. They represent the
operations or tasks that can be performed on the object's data.
Methods are declared within a class and can access the class's attributes and other methods.
They can also have parameters and return values. Methods provide a way to encapsulate
reusable code and promote code organization and modularity.

2. Here's an example program to demonstrate the concept of methods:


// Class with methods
class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
public double divide(double num1, double num2) {
return num1 / num2;
}

public String greet(String name) {


return "Hello, " + name + "!";
}
}

public class MethodsDemo {


public static void main(String[] args) {
Calculator calculator = new Calculator();

// Invoking methods and printing the results


int sum = calculator.add(5, 3);
System.out.println("Sum: " + sum); // Output: Sum: 8

double result = calculator.divide(10.0, 2.5);


System.out.println("Result: " + result); // Output: Result: 4.0

String greeting = calculator.greet("John");


System.out.println(greeting); // Output: Hello, John!
}
LABORATORY EXERCISE 9
ANSWERS
1. Operator overloading in object-oriented programming refers to the ability to
redefine the behavior of an operator when applied to objects of a class. It allows
operators such as `+`, `-`, `*`, `/`, etc., to be used with objects, enabling custom
operations to be performed on those objects.
In Java, operator overloading is not directly supported as it is in some other programming
languages like C++. However, Java does provide a limited form of operator overloading for
certain operators, such as `+` for string concatenation and `+`, `-`, `*`, `/` for numerical types.
These operators can be used with objects of their respective classes, but the behavior is
predefined and cannot be customized.

2. Here's an example program that demonstrates the limited form of operator


overloading in Java:
// Class with operator overloading (limited form)
class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// Addition operator overloading
public ComplexNumber add(ComplexNumber other) {
double newReal = this.real + other.real;
double newImaginary = this.imaginary + other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
// String representation of the complex number
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}
public class OperatorOverloadingDemo {
public static void main(String[] args) {
ComplexNumber num1 = new ComplexNumber(3.5, 2.7);
ComplexNumber num2 = new ComplexNumber(2.1, 1.3);
ComplexNumber sum = num1.add(num2);
System.out.println("Sum: " + sum); // Output: 5.6 + 4.0i
}
}
LABORATORY EXERCISE 10
ANSWERS

1. The purpose of a constructor in object-oriented programming is to initialize the state of


an object when it is created. Constructors are special methods that have the same name
as the class and are called automatically when an object is instantiated.

The main purposes of constructors are:


1. Initializing object state: Constructors initialize the attributes or variables of an object to
their initial values. They ensure that an object starts in a valid and consistent state.
2. Allocating memory: Constructors allocate memory for the object and any resources it
requires. They set up the necessary resources and perform any required setup operations.
3. Providing flexibility: Constructors can accept arguments to initialize the object's attributes
with specific values. They allow different ways to create objects by providing overloaded
constructors with different parameter combinations.

2. Here's an example program that demonstrates the use of constructors:


// Class with constructors
class Person {
private String name;
private int age;

// Default constructor
public Person() {
name = "John Doe";
age = 0;
}

// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getter methods

public String getName() {


return name;
}

public int getAge() {


return age;
}
}

LABORATORY EXERCISE 11
ANSWERS
1. In Java, multiple inheritance refers to the ability of a class to inherit characteristics
and behaviors from multiple parent classes. However, Java does not support multiple
inheritance for classes, meaning a class can only extend a single class. This is done to
avoid the complications and ambiguities that can arise from conflicting method
implementations and member variables.

Here's an example program to demonstrate multiple inheritance using interfaces:


// Interface with method definitions
interface Walkable {
void walk();
}

interface Swimmable {
void swim();
}

// Class implementing multiple interfaces


class Duck implements Walkable, Swimmable {
@Override
public void walk() {
System.out.println("The duck is walking.");
}

@Override
public void swim() {
System.out.println("The duck is swimming.");
}
}

public class MultipleInheritanceDemo {


public static void main(String[] args) {
Duck duck = new Duck();
duck.walk(); // Output: The duck is walking.
duck.swim(); // Output: The duck is swimming.
}
}
```

In this program, we have two interfaces: `Walkable` and `Swimmable`. Each interface
declares a single method without providing any implementation.

The `Duck` class implements both the `Walkable` and `Swimmable` interfaces. It
provides the implementation for the `walk()` and `swim()` methods defined in the
interfaces.
In the `main()` method, we create an object of the `Duck` class and invoke the `walk()`
and `swim()` methods. The output demonstrates how the class inherits and
implements behaviors from multiple interfaces, achieving a form of multiple
inheritance

LABORATORY EXERCISE 12
ANSWERS
1. In Java, an abstract method is a method declared in an abstract class or interface that
does not have an implementation. It provides a method signature without any method
body. The purpose of an abstract method is to define a contract that must be
implemented by the subclasses or implementing classes.

Abstract methods serve as placeholders for behavior that must be defined by concrete
classes. They provide a way to enforce a specific method signature and ensure that
subclasses provide their own implementation of the method.

2. Here's an example program to demonstrate abstract methods:

```java
// Abstract class with an abstract method
abstract class Shape {
public abstract void draw();
}

// Concrete class implementing the abstract method


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

public class AbstractMethodDemo {


public static void main(String[] args) {
Circle circle = new Circle();
circle.draw(); // Output: Drawing a circle.
}
}
```

In this program, we have an abstract class `Shape` with an abstract method `draw()`. The
`Shape` class provides the method signature without any implementation.

The `Circle` class is a concrete subclass of `Shape` and overrides the `draw()` method,
providing its own implementation to draw a circle.

In the `main()` method, we create an object of the `Circle` class and invoke the `draw()`
method. The output demonstrates how the abstract method in the abstract class is
implemented by the concrete subclass.

The program illustrates how abstract methods define a contract that must be fulfilled by
subclasses. Abstract methods play a crucial role in defining the behavior of abstract
classes and interfaces, allowing for polymorphism and providing a structure for the
implementation of specific methods by subclasses.

You might also like