Reputation: 302
I am trying to run the following simple code,
public abstract class Shape{
abstract double area();
abstract double circumference();
public void show()
{
System.out.println("Area = "+area());
System.out.println("Circumference = "+circumference());
}
}
public class Circle extends Shape{
double r;
public double area()
{
return 3.14*r*r;
}
double circumference()
{
return 2*3.14*r;
}
Circle(double radius)
{
r=radius;
}
}
public class Rectangle extends Shape{
double x,y;
double area()
{
return x*y;
}
double circumference()
{
return 2*(x+y);
}
Rectangle(double length, double width)
{
x = length;
y = width;
}
}
public class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
But I keep getting identifier expected error from Java compiler. What am I doing wrong. Everything is public and there seems to be no syntax error. Please help.
Upvotes: 0
Views: 2320
Reputation: 13139
Add the main method:
public class Geometry
{
public static void main(String[] args) {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}
Upvotes: 2
Reputation: 533492
Your call to r.show();
is not in a code block. I suspect you intended to place this is a main method
public static void main(String... args) {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Upvotes: 4
Reputation: 1500225
This is the problem:
class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Your final statement doesn't declare a variable - it's just a statement. That needs to belong in an initializer block, constructor or method. For example:
public class Geometry {
public static void showCircle() {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}
Note that this has nothing to do with inheritance - this code will give the same problem:
class Test {
System.out.println("Oops");
}
Upvotes: 6