Reputation: 1223
An abstract class has a variable and a method.A class extends the abstract class as follows:
abstract class shape
{
int area;
void printArea(){System.out.println("Area = "+area);}
}
class circle extends shape
{
int r;
circle(int a){r = a;}
area=r*r;//line 22
}
public class Abstraction{
public static void main(String[] args) {
circle c=new circle(10);
c.printArea();
}
}
Line 22 gives a compilation error.But if this line is moved into the constructor of the class it compiles
class circle extends shape
{
int r;
circle(int a){r = a;area=r*r;}
}
What is this behaviour?
Upvotes: 0
Views: 3480
Reputation: 121
You cannot call any type of expression in java class body. Only expressions participating in assignment can got directly in java class body.
But if you really want to go that way you could do the following.
class circle extends shape
{
int r;
circle(int a){r = a;}
{
area=r*r;//line 22
}
}
But this code will not work as you expected because of the Java object creation lifecycle.
What will happen is.
So finally
r = a;
area = 0;
Upvotes: 1
Reputation: 3105
area=r*r;//line 22
is not in a function, but in the body of the class.
You can't have a statement in the body like that. You either wrap it up in a static block or move it to a method. But since area is an instance variable, you can not have it in a static block either.
When you move it a method it compiles fine because it is where it belongs.
Take a close look at the structure of a java class.
Upvotes: 3