java @override标注的作用

@Override annotation in Java

BY CHAITANYA SINGH | FILED UNDER: JAVA TUTORIALS

@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method. Here we will discuss why we should use @Override annotation and why it is considered as a best practice in java coding.

Lets take an example first to understand how it is used then we will discuss it in detail:

Example

class ParentClass
{
	public void displayMethod(String msg){
		System.out.println(msg);
	}
}
class SubClass extends ParentClass
{
	@Override
	public void displayMethod(String msg){
		System.out.println("Message is: "+ msg);
	}
	public static void main(String args[]){
		SubClass obj = new SubClass();
		obj.displayMethod("Hey!!");
	}
}

In the above example we are overriding a method displaymethod() in the child class. Even if we don’t use the @Override annotation, the program would still run fine without any issues, You would be wondering the why do we use this annotation at all. Lets discuss about it:

Why we use @Override annotation

Using @Override annotation while overriding a method is considered as a best practice for coding in java because of the following two advantages:

1) If programmer makes any mistake such as wrong method name, wrong parameter types while overriding, you would get a compile time error. As by using this annotation you instruct compiler that you are overriding this method. If you don’t use the annotation then the sub class method would behave as a new method (not the overriding method) in sub class.

2) It improves the readability of the code. So if you change the signature of overridden method then all the sub classes that overrides the particular method would throw a compilation error, which would eventually help you to change the signature in the sub classes. If you have lots of classes in your application then this annotation would really help you to identify the classes that require changes when you change the signature of a method.

转载自:https://beginnersbook.com/2014/07/override-annotation-in-java/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值