Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
giuseppe prinno
5,060 Points@Override
In the java course, Craig talks about Override, but I can't really understand it. Can someone explain it simply? I don't get what it is, when do I need it and what are they used for Please help for I am stuck
2 Answers
Isaiah Marin
11,971 PointsHi,
So there are basically two things happening. One, you are overriding an already created method. Second, the annotation @Override provides safety because when the code is ran it will be double checked that you are indeed overriding an already made method.
For example, you have a class named Animal (the superclass) and you create a subclass called Dog. Since the Dog class is a subclass of the Animal class (the dog's superclass) you may want to use a method from the Animal class. A way to do that is to use the @Override annotation.
Here is a link with some examples. http://www.codejava.net/java-core/the-java-language/override-annotation-examples
Hope this helps.
Fahad Mutair
10,359 Pointsmost of the time you will see @Override annotation with the following methods but there are many , i have to example down
toString
which is inherited from Object class
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
so we put Override to use our method instead of the Object.java (super class) toString method
we can change it to this code instead
@Override
public String toString() {
return "HelloWorld{}";
}
equals
also can be inherited from Object class
public boolean equals(Object obj) {
return (this == obj);
}
so we can change it to this method below here, instead of using Object.java method , the override annotation will make the compiler to use the annotated 1 with Override instead of using the non-annotated method
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
giuseppe prinno
5,060 Pointsgiuseppe prinno
5,060 Pointscan you please explain the annotation @override better please