0% found this document useful (0 votes)
3 views32 pages

Basis Java

The document contains multiple Java programming tasks, including generating Fibonacci series, finding roots of quadratic equations, converting temperatures, calculating averages, and finding the second smallest element in an array. It also covers concepts such as abstract classes, method overloading, file handling, and inheritance. Each task is accompanied by code examples and expected outputs.

Uploaded by

sancharim2233
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)
3 views32 pages

Basis Java

The document contains multiple Java programming tasks, including generating Fibonacci series, finding roots of quadratic equations, converting temperatures, calculating averages, and finding the second smallest element in an array. It also covers concepts such as abstract classes, method overloading, file handling, and inheritance. Each task is accompanied by code examples and expected outputs.

Uploaded by

sancharim2233
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
You are on page 1/ 32

2. Write a java program to print the Fibonacci series.

Answer:

import java.util.Scanner;
public class Solution2 {
​ public static void main(String[] args) {
​ ​ Scanner scanner = new Scanner(System.in);
​ ​ System.out.print("Enter the number of terms for the Fibonacci series: ");
​ ​ int terms = scanner.nextInt();
​ ​ if (terms <= 0) {
​ ​ ​ System.out.println("Please enter a positive integer.");
​ ​ } else {
​ ​ ​ System.out.println("Fibonacci series up to " + terms + " terms:");
​ ​ ​ int first = 0, second = 1;
​ ​ ​ for (int i = 1; i <= terms; i++) {
​ ​ ​ ​ System.out.print(first + " ");
​ ​ ​ ​ int next = first + second;
​ ​ ​ ​ first = second;
​ ​ ​ ​ second = next;
​ ​ ​ }
​ ​ }
​ }
}

Output:
Enter the number of terms for the Fibonacci series: 5
Fibonacci series up to 5 terms: 0 1 1 2 3
3. Write a java program to find the roots of a quadratic equation.

Answer:

public class Solution3 {

public static void main(String[] args) {


double a = 1, b = -3, c = 2;
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Roots are real and different:");
System.out.println("Root 1 = " + root1);
System.out.println("Root 2 = " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("Roots are real and same:");
System.out.println("Root = " + root);
} else {
System.out.println("Roots are complex:");
System.out.println("No real roots exist.");
}
}
}

Output:

Roots are real and different:


Root 1 = 2.0
Root 2 = 1.0
1. Write a java program to convert centigrade temperature into its equivalent Fahrenheit
using command line argument.

Answer:

public class CelsiusToFahrenheit {


​ public static void main(String[] args) {
​ ​ if (args.length == 0) {
​ ​ System.out.println("Invalid input.");
​ ​ return;
​ }
​ double celsius = Double.parseDouble(args[0]);
​ double fahrenheit = (celsius * 9 / 5) + 32;
​ System.out.println(celsius + "°C is equal to " + fahrenheit + "°F");
​ }
}

Output:
100
100.0°C is equal to 212°F
4. Using java command line argument finds the average of any given set of numbers.

Answer:

public class AverageOfNumbers {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide numbers as command-line arguments.");
return;
}
double sum = 0;
for (String num : args) {
sum += Double.parseDouble(num);
}
double average = sum / args.length;
System.out.println("Average: " + average);
}
}

Output:

java Q4 2 5 7 16 20
Average: 10.0

5. Write a Java program to find the second smallest element in an array.

Answer:

import java.util.Arrays;

public class SecondSmallest {



​ public static void main(String[] args) {
​ ​ int[] numbers = {7, 2, 5, 1, 3};
​ ​ if (numbers.length < 2) {
​ ​ ​ System.out.println("Array must have at least two elements.");
​ ​ ​ return;
​ ​ }
​ ​ Arrays.sort(numbers);
​ ​ System.out.println("Second smallest element: " + numbers[1]);
​ }
}

Output:

Second smallest element: 2


6. Using for loop write a program to print the multiplication table of a given number on the
screen screen. Write a program to demonstrate abstract class and abstract method.

Answer:

import java.util.Scanner;

abstract class Animal {


​ abstract void sound();
​ void info() {
​ ​ System.out.println("This is an abstract class example.");
​ }
}

class Dog extends Animal {


​ void sound() {
​ ​ System.out.println("Dog barks.");
​ }
}

class Cat extends Animal {


​ void sound() {
​ ​ System.out.println("Cat meows.");
​ }
}

public class Solution6{


​ public static void main(String[] args) {
​ ​ Scanner sc = new Scanner(System.in);
​ ​ System.out.print("Enter a number: ");
​ ​ int num = sc.nextInt();
​ ​ System.out.println("Multiplication Table for " + num + ":");
​ ​ for (int i = 1; i <= 10; i++) {
​ ​ System.out.println(num + " x " + i + " = " + (num * i));
​ ​ }

​ Animal dog = new Dog();


​ Animal cat = new Cat();
​ dog.sound();
​ cat.sound();

​ }
}
Output:

Enter a number: Multiplication Table for 5:


5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Dog barks.
Cat meows.
7. Write a program to find the even sum and the odd sum in a given array. Write a program
demonstrate method overloading.

Answer:

class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}

public class EvenOddSum {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
int evenSum = 0, oddSum = 0;
for (int num : arr) {
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);


​ Calculator calc = new Calculator();
​ System.out.println("Sum (int, int): " + calc.add(5, 10));
​ System.out.println("Sum (double, double): " + calc.add(2.5, 3.5));
​ System.out.println("Sum (int, int, int): " + calc.add(1, 2, 3));
}
}

Output:

Even Sum: 20
Odd Sum: 16

Sum (int, int): 15


Sum (double, double): 6.0
Sum (int, int, int): 6
8. Write a program in Java which creates a file reference and finds the following:
(i) Path of the file. (ii) Whether file exists or not. (iii) Size of the file.

Answer:

import java.io.File;
public class FileInfo {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println("Path: " + file.getAbsolutePath());
System.out.println("Exists: " + file.exists());
if (file.exists()) {
System.out.println("Size: " + file.length() + " bytes");
}
}
}

Output:

Exists: true
Size: 0 bytes

9. Write a java program to calculate the following series,


1− x /1! + x 2/ 2! − ⋯ 𝑢𝑝𝑡𝑜 𝑛 𝑡𝑒𝑟𝑚𝑠

Answer:

Import java.util.*;

public class SeriesCalculation {


​ public static void main(String[] args) {
​ ​ Scanner sc=new Scanner(System.in);
​ ​ double x=sc.nextDouble();
​ ​ int n = sc.nextInt();
​ ​ double result = 1, term = 1;
​ ​ for (int i = 1; i < n; i++) {
​ ​ ​ term *= x / i;
​ ​ ​ result += (i % 2 == 0 ? term : -term);
​ ​ }
​ ​ System.out.println("Result of the series: " + result);
​ }
}

Output:
Result of the series: 0.33333333333333337
10. Write a java program to create an abstract class named Shape that contains two integers
and an empty method named printArea(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each
one of the classes contain only the method printArea( ) that prints the area of the
given shape.

Answer:

import java.util.Scanner;

abstract class Shape {


int dimension1;
int dimension2;

public Shape(int dimension1, int dimension2) {


this.dimension1 = dimension1;
this.dimension2 = dimension2;
}

abstract void printArea();


}

class Rectangle extends Shape {

public Rectangle(int length, int breadth) {


super(length, breadth);
System.out.println("A Rectangle Created");
}

void printArea() {
int area = dimension1 * dimension2;
System.out.println("Area of Rectangle: " + area);
}
}

class Triangle extends Shape {

public Triangle(int base, int height) {


super(base, height);
System.out.println("A Triangle Created");
}

void printArea() {
double area = 0.5 * dimension1 * dimension2;
System.out.println("Area of Triangle: " + area);
}
}

class Circle extends Shape {


public Circle(int radius) {
super(radius, 0);
System.out.println("A Circle Created");
}

void printArea() {
double area = Math.PI * dimension1 * dimension1;
System.out.println("Area of Circle: " + area);
}
}

public class Solution10 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of the rectangle: ");


int length = scanner.nextInt();
System.out.print("Enter the breadth of the rectangle: ");
int breadth = scanner.nextInt();
Shape rectangle = new Rectangle(length, breadth);
rectangle.printArea();

System.out.print("Enter the base of the triangle: ");


int base = scanner.nextInt();
System.out.print("Enter the height of the triangle: ");
int height = scanner.nextInt();
Shape triangle = new Triangle(base, height);
triangle.printArea();

System.out.print("Enter the radius of the circle: ");


int radius = scanner.nextInt();
Shape circle = new Circle(radius);
circle.printArea();

scanner.close();
}
}
Output:

Enter the length of the rectangle: 10


Enter the breadth of the rectangle: 5
A Rectangle Created
Area of Rectangle: 50
Enter the base of the triangle: 4
Enter the height of the triangle: 6
A Triangle Created
Area of Triangle: 12.0
Enter the radius of the circle: 7
A Circle Created
Area of Circle: 153.93804002589985
11.Write a program in Java to define a class Number with appropriate data members and
member functions to input n number of integers and swap the biggest and smallest
elements. Use member functions read(), swap() and display().

Answer:

import java.util.Scanner;
class Number {
private int[] numbers;
public void read(int n) {
Scanner sc = new Scanner(System.in);
numbers = new int[n];
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
numbers[i] = sc.nextInt();
}
}
public void swap() {
if (numbers == null || numbers.length < 2) return;
int maxIndex = 0, minIndex = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > numbers[maxIndex]) maxIndex = i;

int temp = numbers[maxIndex];


numbers[maxIndex] = numbers[minIndex];
numbers[minIndex] = temp;
}
public void display() {
System.out.println("Array after swapping:");
for (int num : numbers) { System.out.print(num + " ");
}
}
}
public class SwapNumbers {
public static void main(String[] args) {
Number numObj = new Number(); numObj.read(5);
numObj.swap();
numObj.display();
}
}

Output:

Enter 5 integers: 5 10 2 50 3
Array after swapping:
5 10 50 2 3
12. Write a program in java using inheritance to show how to call the base class
parameterized constructors from the derived class using super.

Answer:

class Base {
Base(int a) {
System.out.println("Base class constructor called with value: " + a);
}
}
class Derived extends Base {
Derived(int a, int b) {
super(a);
System.out.println("Derived class constructor called with value: " + b);
}
}
public class InheritanceExample {
public static void main(String[] args) {
Derived obj = new Derived(10, 20);
}
}

Output:

Base class constructor called with value: 10


Derived class constructor called with value: 20
13. Using for loop write a program to print the multiplication table. Write a program to find
the even sum and odd sum in array.
Answer:

public class Solution13 {


public static void main(String[] args) {
int num = 5;
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
​ int[] arr = {1, 2, 3, 4, 5};
int evenSum = 0, oddSum = 0;
for (int num : arr) {
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);
}
}

Output:

5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Even Sum: 6
Odd Sum: 9
14. Write a program to demonstrate method overriding. Write a program to concatenate two
strings.

A.Answer:

class Parent {
void display() {
System.out.println("This is the parent class method.");
}
}
class Child extends Parent {
void display() {
System.out.println("This is the child class method.");
}
}
public class MethodOverridingExample {
public static void main(String[] args) {
Parent obj = new Child();
obj.display();
}
}

Output:

This is the child class method.

B.Answer:

public class StringConcatenation {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
System.out.println("Concatenated String: " + result);
}
}

Output:

Concatenated String: Hello World


15. Write a program to demonstrate multiple inheritance. Write a program to overload `sum`
method.

Answer:

interface A {
void methodA();
}
interface B {
void methodB();}
class C implements A, B {
public void methodA() {
System.out.println("Method A from interface A");
}
public void methodB() {
System.out.println("Method B from interface B");
}
}
class SumCalculator {
int sum(int a, int b) {
return a + b;
}
double sum(double a, double b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
public class MultipleInheritanceExample {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
SumCalculator calc = new SumCalculator();
System.out.println("Sum (int, int): " + calc.sum(5, 10));
System.out.println("Sum (double, double): " + calc.sum(2.5, 3.5));
System.out.println("Sum (int, int, int): " + calc.sum(1, 2, 3));

}
}

Output:
Method A from interface A
Method B from interface B
Sum (int, int): 15
Sum (double, double): 6.0
Sum (int, int, int): 6
17,18: Write a program to demonstrate constructor overloading & default constructor. Write
a complete Java program to print the Fibonacci series up to n terms. Input should
be taken using Buffered Reader class, Exception must be handled with custom
error message.

A.Answer:

class SolutionA {
int value;
DemoConstructor() {
value = 0;
System.out.println("Default Constructor called. Value = " + value);
}
DemoConstructor(int value) {
this.value = value;
System.out.println("Overloaded Constructor called. Value = " + value);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
DemoConstructor obj1 = new DemoConstructor();
DemoConstructor obj2 = new DemoConstructor(42);
}
}
Output:
Enter the number of terms:10
B.Answer:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FibonacciBufferedReader {


public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter the number of terms: ");
int n = Integer.parseInt(br.readLine());
int a = 0, b = 1;
System.out.println("Fibonacci Series:");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}

catch (IOException | NumberFormatException e) {


System.out.println("Invalid input. Please enter a valid number.");
}
}
}
Output:

Enter the number of terms: 7


Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
19. Write a complete Java program to calculate factorial of a number, input should be passed
through command line argument. Write a program to describe Default constructor &
Overloaded constructor.

A.Answer

public class Solution19{


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a number as a command-line argument.");
return;
}
int num = Integer.parseInt(args[0]);
int fact = 1;

for (int i = 1; i <= num; i++) {


fact *= i;
}
System.out.println("Factorial of " + num + " is " + fact);
}
}

Output:

$ javac Solution19.java
$ java Solution19.java 5
>>> Factorial of 5 is 120
B.Answer

class Solution19B{
private String name;
private int age;

public ConstructorExample() {
name = "Unknown";
age = 0;
System.out.println("Default constructor called.");
}

public ConstructorExample(String name) {


this.name = name;
this.age = 0;
System.out.println("Overloaded constructor with one parameter called.");
}

public ConstructorExample(String name, int age) {


this.name = name;
this.age = age;
System.out.println("Overloaded constructor with two parameters called.");
}

public void displayDetails() {


System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


ConstructorExample obj1 = new ConstructorExample();
obj1.displayDetails();

ConstructorExample obj2 = new ConstructorExample("Alice");


obj2.displayDetails();

ConstructorExample obj3 = new ConstructorExample("Bob", 25);


obj3.displayDetails();
}
}

Output:

Default constructor called.


Name: Unknown, Age: 0
Overloaded constructor with one parameter called.
Name: Alice, Age: 0
Overloaded constructor with two parameters called.
Name: Bob, Age: 25
20. Write a program to demonstrate Deep copy & Shallow copy. Write an exception subclass
which throws an exception if the variable "age" passed as an argument to a method
and the value of age is less than 30.

A.Answer:

class ShallowCopy {
int[] arr;
ShallowCopy(int[] arr) {
this.arr = arr;
}
}
class DeepCopy {
int[] arr;
DeepCopy(int[] arr) {
this.arr = arr.clone();
}
}

public class CopyExample {


public static void main(String[] args) {
int[] original = {1, 2, 3};
ShallowCopy shallow = new ShallowCopy(original);
DeepCopy deep = new DeepCopy(original);
original[0] = 99;
System.out.println("Shallow Copy: " + shallow.arr[0]);
System.out.println("Deep Copy: " + deep.arr[0]);
}
}
Output:
Shallow Copy: 99
Deep Copy: 1
B.Answer:
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static void checkAge(int age) throws AgeException {
if (age < 30) {
throw new AgeException("Age is less than 30, not allowed.");
} else {
System.out.println("Age is valid: " + age);
}
}
public static void main(String[] args) {
try {
checkAge(25); // Example: Invalid age
} catch (AgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output:

Shallow Copy: 99
Deep Copy: 1
Answer:
Exception caught: Age is less than 30, not allowed
21. Write a program to demonstrate multi catch statement using command line argument.
One object in Java can be assigned as reference to another object of the same type.
To explain this concept write a complete Java program and explain how a reference
object works.

A) Answer:

public class Solution21A {


public static void main(String[] args) {
try {
if (args.length < 2) {
throw new IllegalArgumentException("Please provide two numbers as arguments.");
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Error: Please provide valid numbers.");
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}

Output:

$ javac Solution21A.java
$ java Solution21A.java
>>> Please provide two numbers as arguments.
$ java Solution21A.java ten 5
>>> Error: Please provide valid numbers.
$ java Solution21A.java 10 0
>>> Error: Division by zero is not allowed.
$ java Solution21A.java 10 2
>>> Result: 5
B) Answer:

class Demo{
int value;
Demo(int value) {
this.value = value;
}
}
public class ObjectReferenceExample {
public static void main(String[] args) {
Demo obj1 = newDemo(10);
Demo obj2 = obj1;
obj2.value = 20;
System.out.println("obj1.value: " + obj1.value);
System.out.println("obj2.value: " + obj2.value);
}
}

Output:
obj1.value: 20
obj2.value: 20
22. Write a program to demonstrate multi-level inheritance. Write a program to demonstrate
the method overloading for area() function.

A)Answer:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("This mammal can walk.");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Solution22A {
public static void main(String[] args) {

Dog myDog = new Dog();


myDog.eat();
myDog.walk();
myDog.bark();
}
}

Output:
This animal eats food.
This mammal can walk.
The dog barks.
B)Answer:

class Area{
double area(double side) {
return side * side;
}

double area(double length, double breadth) {


return length * breadth;
}

double area(double side1, double side2, double side3) {


double s = (side1 + side2 + side3) / 2; // Semi-perimeter
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}

public class MethodOverloadingDemo {


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

// Calculate the area of a square


double squareArea = calculator.area(5);
System.out.println("Area of the square: " + squareArea);

// Calculate the area of a rectangle


double rectangleArea = calculator.area(10, 5);
System.out.println("Area of the rectangle: " + rectangleArea);

double area(double side1, double side2, double side3) {


double s = (side1 + side2 + side3) / 2; // Semi-perimeter
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); // Heron's formula
}

Output:

Area of the square: 25.0


Area of the rectangle: 50.0
Area of the triangle: 24.0
23. Write a program to demonstrate Compile time polymorphism and Run time
polymorphism.

Answer:

class Shape {
void area() {
System.out.println("Area of shape is undefined.");
}
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

void area() {
System.out.println("Area of circle: " + (Math.PI * radius * radius));
}
}

class Rectangle extends Shape {


double length, breadth;

Rectangle(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}

void area() {
System.out.println("Area of rectangle: " + (length * breadth));
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Shape shape;
shape = new Circle(7);
shape.area();
shape = new Rectangle(10, 5);
shape.area();
}
}
24. Write a program to instantiate an object without using the "new" keyword. Write a
program to multiply two matrices.

Answer 1:

class Example {
void display() {
System.out.println("Object created without 'new' keyword.");
}
}

public class Main {


public static void main(String[] args) {
Example obj = createObject();
obj.display();
}

static Example createObject() {


return new Example();
}
}

OUTPUT:
Object created without 'new' keyword.

Answer 2:
public class MatrixMultiplication {
public static void main(String[] args) {

int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6}
};

int[][] matrix2 = {
{7, 8},
{9, 10},
{11, 12}
};

int[][] result = new int[2][2];


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("Resultant matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT:

Resultant matrix:
58 64
139 154
25. Write a program to find whether a given string is a palindrome or not using command
line argument.

Answer:

public class Solution25{


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No input provided");
return;
}
String input = args[0];
String reversed = new StringBuilder(input).reverse().toString();
if (input.equals(reversed)) {
System.out.println("The string is a palindrome");
} else {
System.out.println("The string is not a palindrome");
}
}
}

OUTPUT:

$ javac Solution25.java
$ java Solution25.java madam
>>> The string is a palindrome
$ java Solution25.java Helo
>>> The string is not a palindrome
26.Write a Java program which creates a class named "Employee" having the following
members: Name, Age, Phone number, Address, Salary. It also has a method named
'printSalary()' which prints the salary of the Employee. Two classes 'Officer' and
'Manager' classes have data members 'specialisation' and 'department' respectively.
Now, assign name, age, phone number, address and salary to an officer and a
manager by making an object of both of these classes and print the same.

Answer:

class Employee {
​ private String name;
​ private int age;
​ private String phoneNumber;
​ private String address;
​ private double salary;

​ Employee(String name, int age, String phoneNumber, String address, double salary) {
​ ​ this.name = name;
​ ​ this.age = age;
​ ​ this.phoneNumber = phoneNumber;
​ ​ this.address = address;
​ ​ this.salary = salary;
​ }
​ void printSalary() {
​ ​ System.out.println("Salary of " + name + ": " + salary);
​ }
​ void show() {
​ ​ System.out.println("Name: " + name);
​ ​ System.out.println("Age: " + age);
​ ​ System.out.println("Phone Number: " + phoneNumber);
​ ​ System.out.println("Address: " + address);
​ ​ printSalary();
​ }
}
class Officer extends Employee {
​ String specialisation;
​ Officer(String name, int age, String phoneNumber, String address, double salary, String
specialisation) {
​ ​ super(name, age, phoneNumber, address, salary);
​ ​ this.specialisation = specialisation;
​ }
​ void show() {
​ ​ super.show();
​ ​ System.out.println("Specialisation: " + specialisation);
​ }
}
class Manager extends Employee {
​ String department;

​ Manager(String name, int age, String phoneNumber, String address, double salary, String
department) {
​ ​ super(name, age, phoneNumber, address, salary);
​ ​ this.department = department;
​ }

​ void show() {
​ ​ super.show();
​ ​ System.out.println("Department: " + department);
​ }
}

public class Solution26 {


​ public static void main(String[] args) {
​ ​ Employee officer = new Officer("Alice", 35, "9876543210", "123 Street, City",
75000, "IT");
​ ​ Employee manager = new Manager("Bob", 40, "8765432109", "456 Avenue, City",
85000, "Sales");
​ ​ System.out.println("Officer Details:");
​ ​ officer.show();
​ ​ System.out.println("\nManager Details:");
​ ​ manager.show();
​ }
}

Output:

Officer Details:
Name: Alice
Age: 35
Phone Number: 9876543210
Address: 123 Street, City
Salary of Alice: 75000.0
Specialisation: IT

Manager Details:
Name: Bob
Age: 40
Phone Number: 8765432109
Address: 456 Avenue, City
Salary of Bob: 85000.0
Department: Sales

You might also like