Reputation: 13
I want my program to display the area of square and rectangle, as you might have already guessed this is a homework problem so I cant really change the format.
import java.util.*;
abstract class Shape
{
int area;
abstract void area();
}
class Square extends Shape
{
int len;
void area()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the lenght of the square: ");
len=s.nextInt();
}
public void displayarea()
{
Square q= new Square();
q.area();
System.out.println("The area of the square is: "+(len*len));
}
}
class Rectangle extends Shape
{
int l,b;
public void area()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the lenght of the rectangle: ");
l=sc.nextInt();
System.out.println("Enter the breadth of the rectangle: ");
b=sc.nextInt();
}
public void displayarea()
{
Rectangle r = new Rectangle();
r.area();
System.out.println("The area of the rectangle is: "+(l*b));
}
}
public class Postlab
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle();
Square square = new Square();
rectangle.displayarea();
square.displayarea();
}
}
Upvotes: 0
Views: 48
Reputation: 4841
The problem is that you are calling area on the wrong object.
public void displayarea() {
Square q = new Square();
q.area();
System.out.println("The area of the square is: " + (len * len));
}
When you call this on a square A it first creates a square B and calls B.area(). Because of this when you reach area calculation, result is 0. All values are set on square B while values of square A remain unset.
Instead you want to call area on your square A. Like this.
public void displayarea() {
area();
System.out.println("The area of the square is: " + (len * len));
}
Upvotes: 1
Reputation: 4582
In your code displayarea()
method, you are creating new Object of Class (Square/Rectangular) to call area()
method. So the objects to which scanner is assigning values in using area() method is different to which you are printing the area. So technically area()
and displayarea()
are being called on different objects of class. So you are always getting null or 0. Data assigned in one object is not shared by another objects. (until the variables are not declared as static, static variables shared between all instance of class)
So your code should be updated as below(same applied to Rectangle):
public void displayarea() {
area();
System.out.println("The area of the square is: " + (len * len));
}
Upvotes: 1