-
Override methods
Hi there,
I'd like to ask a question. In one of tutorials on java applet I've been read, it gave an example:
public class FirstApplet extends Applet {
Image NewImage(){
public void init() {
...
And it said, that the line with method's name "init" is overriding the method "init" of Applet class.
Can you please explain me, what does it mean in java "to override a method"?
-
-
Overriding a method in Java is making it more specific to the subclass.
Let me give you an example.
A given class called Rectangle and a method that returns its area:
Code:
public class Rectangle {
...
public double area() { return a*b; } // Being [I]a[/I] and [I]b[/I] the size of heigh and weight.
...
}
Now we have a class called Square which is a specific class of Rectangle:
Code:
public class Square extends Rectangle {
...
public double area() { return Math.pow(a, 2); } // Being [I]a[/I] the size of its side.
...
}
As you can see we overrode the method area in the subclass Square which inherits from Rectangle. Now if we create an object Square and call its method area it will execute the method in Square.
If we hadn't define the method area in Square and we still create a Square object and call the area method, the code from Rectangle would be executed.