Let's say I have a method called mymethod()
and this method overrides the method of the super class method.
What does it mean to override a method?
Does that mean mymethod() ignores everything that is in the method of the superclass, or does that means mymethod() also includes everything in the superclass method?
When overriding a method, can I only override the methods of the same name, or I can override methods of any name?
thanks.
An example:
public class Base {
public void saySomething() {
System.out.println("Hi, I'm a base class");
}
}
public class Child extends Base {
#Override
public void saySomething() {
System.out.println("Hi, I'm a child class");
}
}
Now assume we have a main function somewhere...
public static void main(String [] args) {
Base obj = new Child();
obj.saySomething();
}
When this runs, it will call Child's version of saySomething, because you overrode the parent's version by giving a new version of the function in Child.
The #Override annotation allows other developers (and you, when you forget) to know that this method overrides something in a base class/interface, and it also allows the compiler to yell at you if you're not actually overriding anything in a base class. For example, if you got the number of arguments wrong for a function, the compiler will give you an error saying your #Override is incorrect.
For example:
public class Child extends Base {
#Override
public void saySomething(int x) {
System.out.println("I'm a child and x is: " + x);
}
}
The compiler will yell at you because this version of saySomething takes an argument, but the parent's version doesn't have an argument, so you're #Override-ing something that's not in the parent.
On super
The Child version of saySomething will not invoke the Base version, you have to do it yourself with super.method().
For example:
public class Child extends Base {
#Override
public void saySomething() {
super.saySomething();
System.out.println("I'm also a child");
}
}
If you ran the main and used this Child class, it would print out I'm a base and I'm also a child.
Overriding means that when you call a method on your object, your object's method is called instead of the super class. The #Override annotation is something you use to make sure that you are overriding the correct method of the superclass. If you annotate a method that does not exist in the superclass, the Java compiler will give you an error. This way you can be sure that you are overriding the correct methods. This is especially useful in cases like this:
public class MyClass {
...
public boolean equals(MyClass myClass) {
...
}
}
There is a logic-bug in the code above. You haven't actually overridden the Object class's equals method. If you add the #Override annotation:
public class MyClass {
...
#Override
public boolean equals(MyClass myClass) {
...
}
}
The Java compiler will now complain because there is no corresponding method in the parent class. You'll then know that the correct solution is:
public class MyClass {
...
#Override
public boolean equals(Object o) {
...
}
}
To call the parent class's method, you can call super.overriddenMethod() where overriddenMethod is the name of the method you have overridden. So if you want to do something in addition to what the parent class already does, you can do something like this:
public class MyClass {
...
#Override
public void overriddenMethod() {
super.overriddenMethod();
/* whatever additional stuff you want to do */
}
}
If an inheriting class has on override method of the same name as the parent class it will be called instead of the one in the parent class. This only works if the names are the same, and of course if the signature of the method matches your call to the method.
What does it mean to override a method?
It means you replace the super class definition of the method with your own definition.
does that mean mymethod() ignores everything that is in the method of the super class?
or does that means mymethod() also includes everything in the superclass method?
You can choose whether to include the super class definition within your definition. To include it, you need to call super.mymethod() within mymethod().
and when overriding a method, can I only override the methods of the same name, or I can override methods of any name?
To override a method, you must supply a method in the sub class with the same signature (which means the same name, parameters and return type).
As a side note, the #Override annotation in your question does not actually cause your method to override another method. It causes a compile-time error if a method annotated with it does not have a signature matching a public or protected method of a super class (or interface as of 1.6).
I once had a student come to ask me why his code wasn't working. He had spent several days wondering why he could put something into a collection but was not able to find it. His code was something like:
public int hashcode()
instead of:
public int hashCode()
So the hashCode method never got called.
Adding #Overrides to a method makes it clear that you are overriding the method AND make sure that you really are overriding a method.
When you override a method of the super class, calling that method on your object calls its method instead of that of the super class.
You can call the super class's method (despite having overridden it) using super.methodName(). A common reason for this is when the overridden method would otherwise reimplement the super class method and add additional code specific to the extending class (public void methodName() { super.methodName(); /* more code */ }).
#Override annotation allows you to cause warning at compile time if the method isn't actually overriding anything. It isn't necessary, but these warning are a hit to you that you might have got the signature wrong in the extending class, forgot to implement the method at all in the super class, or some other silly mistake.
Related
How to call a base class method. In the method "test" of the "invoke" class, I'm trying to upcast to the base type to call exactly its method, but for some reason I have an equal call to the derived method
class BaseClass {
protected void print(){
System.out.println("This is method print from BaseClass");
}
}
class DerivedClass extends BaseClass{
#Override
protected void print() {
System.out.println("This is method print from DerivedClass");
}
}
public class invokeDrawing{
public void test() {
DerivedClass derived = new DerivedClass();
derived.print();
System.out.println("****************");
BaseClass derivedTest = (BaseClass)derived;
derivedTest.print();
}
}
You could add a method on it which would call the superclass method specifically, like this:
public void superPrint() {
super.print();
}
And then call it from your derived class:
derived.superPrint();
Java polymorphism works differently than you expect. When a method of an object is called, the 'most specific' method is invoked, unless specified otherwise. This makes sense, because you always want your object to behave the way the implementation intends, and not the way the base class intends (because the base class does not know the specific class - In other words, you have more context in the derived class, and therefore that behavior is more applicable).
In your example, the object is still of type DerivedClass despite you 'casting' it to BaseClass. The casting only shrouds the fact that you actually have a DerivedClass-Object, but the behavior still comes from the method overriden in DerivedClass.
If you want to invoke a super-method from a derived class, you can use the super keyword:
public String toString() {
return "123 " + super.toString();
}
There are hacks to work around this, if you really, really need it, but usually you don't.
I'm currently learning about class inheritance in my Java course and I don't understand when to use the super() call?
Edit:
I found this example of code where super.variable is used:
class A
{
int k = 10;
}
class Test extends A
{
public void m() {
System.out.println(super.k);
}
}
So I understand that here, you must use super to access the k variable in the super-class. However, in any other case, what does super(); do? On its own?
Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.
However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal {
private final String noise;
protected Animal(String noise) {
this.noise = noise;
}
public void makeNoise() {
System.out.println(noise);
}
}
public class Pig extends Animal {
public Pig() {
super("Oink");
}
}
super is used to call the constructor, methods and properties of parent class.
You may also use the super keyword in the sub class when you want to invoke a method from the parent class when you have overridden it in the subclass.
Example:
public class CellPhone {
public void print() {
System.out.println("I'm a cellphone");
}
}
public class TouchPhone extends CellPhone {
#Override
public void print() {
super.print();
System.out.println("I'm a touch screen cellphone");
}
public static void main (strings[] args) {
TouchPhone p = new TouchPhone();
p.print();
}
}
Here, the line super.print() invokes the print() method of the superclass CellPhone. The output will be:
I'm a cellphone
I'm a touch screen cellphone
You would use it as the first line of a subclass constructor to call the constructor of its parent class.
For example:
public class TheSuper{
public TheSuper(){
eatCake();
}
}
public class TheSub extends TheSuper{
public TheSub(){
super();
eatMoreCake();
}
}
Constructing an instance of TheSub would call both eatCake() and eatMoreCake()
When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:
http://download.oracle.com/javase/tutorial/java/IandI/super.html
You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.
Super will call your parent method. See: http://leepoint.net/notes-java/oop/constructors/constructor-super.html
You call super() to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super() or super(param,param) oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.
The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.
I just tried it, commenting super(); does the same thing without commenting it as #Mark Peters said
package javaapplication6;
/**
*
* #author sborusu
*/
public class Super_Test {
Super_Test(){
System.out.println("This is super class, no object is created");
}
}
class Super_sub extends Super_Test{
Super_sub(){
super();
System.out.println("This is sub class, object is created");
}
public static void main(String args[]){
new Super_sub();
}
}
From oracle documentation page:
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.
You can also use super to refer to a hidden field (although hiding fields is discouraged).
Use of super in constructor of subclasses:
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Related post:
Polymorphism vs Overriding vs Overloading
There something ambiguous about this idea and I need some clarifications.
My problem is when using this code:
public class B {
private void don() {
System.out.println("hoho private");
}
public static void main(String[] args) {
B t = new A();
t.don();
}
}
class A extends B {
public void don() {
System.out.println("hoho public");
}
}
The output is hoho private.
Is this because the main function is in the same class as the method don, or because of overriding?
I have read this idea in a book, and when I put the main function in another class I get a compiler error.
You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the #Override annotation when you intend to override,
class A extends B {
#Override
public void don() { // <-- will not compile if don is private in B.
System.out.println("hoho public");
}
}
In this case why didn't compiler provide an error for using t.don() which is private?
The Java Tutorials: Predefined Annotation Types says (in part)
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with #Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
is this because the main function is in the same class as the method "don"
No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.
No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.
You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.
Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A
private members aren't visible to any other classes, even children
You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.
public class A
{
private int calculate() {return 1;}
public void visibleMethod()
{
System.out.println(calculate());
};
}
public class B extends A
{
private int calculate() {return 2;}
public void visibleMethod()
{
System.out.println(calculate());
};
}
If you call A.visibleMethod() it prints out 1.
If you call B.visibleMethod() it prints 2.
If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.
consider the following code in java:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
The output obtained is the following:
Printed in Superclass
Printed in Subclass
If the subclass is overriding why is superclass println still displaying on screen?
It is not suppose only to display the content of the method on the subclass?
Why is super not being invoked in the following code if the method is overriding?
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
1 Because of the first line in the method super.printMethod();
2 Because there is no call to a super method.
if the subclass is overriding why is superclass println still displaying on screen?
Because you called super.printMethod(). That calls the parent class implementation of printMethod().
why is super not being invoked in the following code if the method is overriding?
Because the developer didn't need, or didn't want the code in the parent class to execute- he wanted to rewrite the method entirely. You might also see the override keyword used when the parent implementation isn't defined, such as with an interface or an abstract class.
Calling the parent class implementation of a method isn't required.
if the subclass is overriding why is superclass println still
displaying on screen? it is not suppose only to display the content of
the method on the subclass?
This line:
super.printMethod();
Will call the super class's printMethod(). This will essentially become:
new Superclass().printmethod();
You don't need to call super to do an override. Do this instead:
// overrides printMethod in Superclass
public void printMethod() {
//super.printMethod();
System.out.println("Printed in Subclass");
}
Another way to approach your question is to do the following:
public class Superclass {
public void printMethod() {
System.out.println("Printed in " + this.getClass().getName() + ".");
}
}
Then just do:
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();//just do override
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
another question, why is super not being invoked in the following code
if the method is overriding?
You don't need super to do #Override as mentioned above. From this question:
Use it every time you override a method for two benefits. Do it so
that you can take advantage of the compiler checking to make sure you
actually are overriding a method when you think you are. This way, if
you make a common mistake of misspelling a method name or not
correctly matching the parameters, you will be warned that you method
does not actually override as you think it does. Secondly, it makes
your code easier to understand because it is more obvious when methods
are overwritten.
Additionally, in Java 1.6 you can use it to mark when a method
implements an interface for the same benefits. I think it would be
better to have a separate annotation (like #Implements), but it's
better than nothing.
If you want to know more about when to use super with method overrides, then check this article question.
You don't have to call the superclass method with super.printMethod(); to override the method, but you did, so
Printed in Superclass
is printed. To not have it print, remove the call to super.printMethod();; it's not necessary.
For onCreateOptionsMenu, it's not using the overridden functionality, so there's no need to call super.onCreateOptionsMenu.
When you invoke super(), you call the superclass method. The override would still work without "Printed in Superclass" printed if you simply deleted the super() invocation.
why should we widen the accessibility of overridden methods ? If the super class has a protected method and subclass has same method with public. Why should happen?
It's a different method! Subclasses don't inherit private methods! So you're not "overriding" at all. You are simply DEFINING a method with the same name as the private method in the superclass.
class A
{
private void myMethod() { }
}
class B extends A
{
public void myMethod() { } // a completely different method. Has nothing to do with the above method. It is not an override.
}
Because in an object hierarchy, JVM will always run the Overriden method. If your overriden method is not accessible, then it is useless.
public class A{
void A(){}
}
public class B extends A{
private void A(){} //this makes no sence and its impossible
PSV main(String ..){
A a = new B();
a.A(); //error as JVM cannot call overriden method which is private.
}
}
Methods declared as private or static can not be overridden!
Annotation #Override indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
Use it every time you override a method for two benefits. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
And in Java 1.6 you can use it to mark when a method implements an interface for the same benefits.