Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Here are the solutions to the following questions.

Question 1:
```java
class Parent {
private void printMessage() {
System.out.println("This is parent class");
}
}

class Child extends Parent {


void printMessage() {
System.out.println("This is child class");
}
}

public class Main {


public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();

parent.printMessage(); // This line will give an error as 'printMessage' is a private method in the
parent class
child.printMessage();
((Parent) child).printMessage(); // This line will again give an error as 'printMessage' is a private
method
}
}
```

Question 2:
```java
class Rectangle {
private double length;
private double breadth;

Rectangle(double length, double breadth) {


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

double getArea() {
return length * breadth;
}

double getPerimeter() {
return 2 * (length + breadth);
}
}

class Square extends Rectangle {


Square(double side) {
super(side, side);
}
}

public class Main {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(4, 5);

System.out.println("Area of rectangle: " + rectangle.getArea());


System.out.println("Perimeter of rectangle: " + rectangle.getPerimeter());

Square square = new Square(5);

System.out.println("Area of square: " + square.getArea());


System.out.println("Perimeter of square: " + square.getPerimeter());

Square[] squares = new Square[10];

for (int i = 0; i < squares.length; i++) {


squares[i] = new Square(i+1);
System.out.println("Area of square " + (i+1) + ": " + squares[i].getArea());
}
}
}
```

Question 3:
```java
class Shape {
void printShape() {
System.out.println("This is shape");
}
}

class Rectangle extends Shape {


void printShape() {
System.out.println("This is rectangular shape");
}
}

class Circle extends Shape {


void printShape() {
System.out.println("This is circular shape");
}
}

class Square extends Rectangle {


void printSquare() {
System.out.println("Square is a rectangle");
}
}

public class Main {


public static void main(String[] args) {
Square square = new Square();
square.printShape(); // calling the method of 'Shape' class by the object of 'Square' class
square.printSquare();
}
}
```

You might also like