我们可以覆盖java中的main方法吗?
覆盖是实现多态的机制之一。当我们有两个类时,就是这种情况,其中一个类使用extends关键字继承了另一个属性,而这两个类具有相同的方法,包括参数和返回类型(例如sample())。
既然是继承。如果我们实例化子类,则会在子类对象中创建超类成员的副本,因此这两种方法都可用于子类(对象)。
当我们调用此方法(示例)时,JVM会根据用于调用该方法的对象来调用相应的方法。
示例
class Super{
public static void sample(){
System.out.println("Method of the superclass");
}
}
public class OverridingExample extends Super {
public static void sample(){
System.out.println("Method of the subclass");
}
public static void main(String args[]){
Super obj1 = (Super) new OverridingExample();
OverridingExample obj2 = new OverridingExample();
obj1.sample();
obj2.sample();
}
}输出结果
Method of the superclass Method of the subclass
覆盖静态方法
当超类和子类包含相同的方法(包括参数)以及它们是否为静态时。超类中的方法将被子类中的方法隐藏 。
简而言之,这种机制称为方法隐藏,尽管如果父类和子类是静态的,则它们的方法具有相同的签名,但不将其视为覆盖。
覆盖主要方法
您无法覆盖静态方法,并且由于publicstaticvoidmain()方法是静态的,因此我们无法覆盖它。
示例
class Super{
public static void main(String args[]) {
System.out.println("This is the main method of the superclass");
}
}
class Sub extends Super{
public static void main(String args[]) {
System.out.println("This is the main method of the subclass");
}
}public class MainOverridingExample{
public static void main(String args[]) {
MainOverridingExample obj = new MainOverridingExample();
Super.main(args);
Sub.main(args);
}
}输出结果
This is the main method of the superclass This is the main method of the subclass
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短