Reputation: 2347
I am still trying to learn java, so correct me if I'm wrong. As I understand it, the super keyword calls the constructor of a class. So I do not understand what the significance of saying
super.paint(g)
does for example, or more recently while reading about animation I came across
super.addNotify()
I tried looking up documentation on the two (perhaps poorly) and it didn't satisfy my curiosity adequately, so here we are.
Any clarification on those two example or in general would be appreciated. Thanks!
Upvotes: 1
Views: 410
Reputation: 31
All the other answers are pretty clear. But maybe you would like to know why in the first place someone would call super.
Java have an inheritance system, by whom you may derive a class from another, i.e. take the behaviuor and data structures from a class and reuse it in another. The key here is (or was, when it was conceived) is to reuse code you have already written, and extend it in some way.
Upvotes: 1
Reputation: 13327
public class A {
public void pirintStr(){
System.out.print("Hello from A");
}
}
public class B extends A{
public void fun(){
// if you wirte this
printStr(); //this will print Hello from B
//if you want the super class version of this method you can write super keyword
super.printStr();//this will print Hello from A
}
public void printStr(){
System.out.print("Hello from B");
}
}
Upvotes: 1
Reputation: 3443
Let me describe it in code:
public class Parent{
protected void doSomething(){
...
}
}
//notice the extends Parent which is the super
public class Child extends Parent{
public void doSomethingOnParent(){
super.doSomething(); //calls a method on the parent class
}
}
Upvotes: 3
Reputation:
super
is a keyword that is a reference to the superclass of the class from which you are using the keyword.
So super()
calls the constructor of the superclass, super(x)
calls a parameterised constructor, and super.paint(g)
calls the paint()
method of the superclass.
Upvotes: 7
Reputation: 132994
No, the super keyword refers to the base class. So super.f() calls the f() method of the superclass.
In some cases, the superclass privides some basic routines, and when you override the function, you first call the base class's implementation, and then add your custom code. It's the case for both your examples.
Upvotes: 4