Chapter 10 Aditya Satapathy
Chapter 10 Aditya Satapathy
(c) Demonstrate the concept of encapsulation by accessing private fields through the methods.
Program-
package chap10;
class Employee {
this.name = n;
this.id = i;
this.salary = s;
return name;
this.name = name;
return id;
}
public void setId(int id) {
this.id=id;
return salary;
this.salary = salary;
emp1.displayDetails();
emp1.setName("Rabi");
emp1.setId(102);
emp1.setSalary(1500);
System.out.println("Name:"+emp1.getName());
System.out.println("Id:"+getId());
System.out.println("Salary $:"+emp1.getSalary());
emp1.displayDetails();
}
Output-
Q2. (a) Write a Java program to demonstrate the IS-A relationship by creating a Vehicle class and a
subclass Car with additional properties. Add a display() method to show polymorphic behavior.
(b) Implement a HAS-A relationship by adding an Engine class and including it as a property in the
Car class. Add a method startEngine() in the Engine class and call it from the Car class.
(c) Demonstrate polymorphism by creating a list of Vehicle objects (both Vehicle and Car) and
calling the display() method on each object.
Program-
package chap10;
class Vehicle {
String Name;
Engine engine;
Vehicle(String nm) {
this.Name = nm;
void display() {
void startEngine() {
engine.startEngine();
}
class Car extends Vehicle {
Car(String nm) {
super(nm);
C1.display();
C1.startEngine();
C2.display();
C2.startEngine();
class Engine {
void startEngine() {
System.out.println("Engine started.");
Output-
Q3. (a) Write a Java program to create a class Rectangle with attributes length and breadth.
(c) Add a method calculateArea() to compute and return the area of the rectangle.
Program-
package chap10;
this.length=length;
this.breath=breath;
int calculateArea() {
return length*breath;
System.out.println("Area:"+rect1.calculateArea());
}
Output-
Q4. (a) Create a package mypackage containing a class Student with attributes name and
rollNumber.
(c) Add a method displayDetails() in the Student class to print the student's details.
Program-
package mypackage;
String Name;
int rollNumber;
Name=nm;
rollNumber=rn;
void displayDetrails(){
System.out.println("Name:"+this.Name);
System.out.println("Roll Number:"+this.rollNumber);
s1.displayDetrails();
Output-
Q5. (a) Write a program that demonstrates the use of super to call the parent class constructor and
methods.
(b) Create a parent class Animal and a subclass Dog with additional behavior.
(c) Create an interface Speak with a method makeSound(). Implement it in the Animal and Dog
classes to demonstrate polymorphism.
Program-
package chap10;
interface Speak {
void makeSound();
String name;
Animal(String name) {
this.name = name;
String breed;
Dog(String name, String breed) {
super(name);
this.breed = breed;
super.makeSound();
System.out.println("Woof! Woof!");
System.out.println("Fetching...");
myDog.makeSound();
myDog.fetch();
Output-