I am new to Java (reading books for 4 months now). So probably my question can appear too simple. My understanding is that abstract methods don't have a body and can't provide implementation
So how does this works?
public abstract void fillRect (int x, int y, with, height);
I did't point the question clearly. We've got abstract method. Why does it draw a rectangle if I doesn't provide a body, just parameters.
For example
public void paint (Graphics g) {
g.fillRect (5, 5, 30, 30);
}
There are two things you need to know
-declaration : The prototype or structure of the method. e.g:
public int add(int a, int b);
-definition : The implementation of the method
public int add(int a, int b) {
this.a = a;
this.b = b;
return a + b;
}
Now an abstract method can have a declaration i.e a structure or prototype. But it cannot have a definition. The definition should be done in the class which extends the class containing the abstract method:
class A {
public abstract int add(int a,int b); //just declaration- no body
}
class B extends A {
/*must override add() method because it is abstract in class A i.e class B must have a body or definition of add()*/
int a, b;
public int add(int a,int b) {
this.a = a;
this.b = b;
return a + b;
}
}