我们可以覆盖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
热门推荐
1 狗狗技巧训练
3 狗狗倒转训练
5 狗狗厕所怎么训练
6 狗狗训练做
8 狗狗喂养训练
10 声音训练狗狗
11 训练狗狗原理
12 几个月的狗狗开始训练
13 怎样训练狗狗在家里大小便
14 训练狗狗词语
15 简单训练狗狗
16 口语训练狗狗
17 英语听力训练狗狗
18 警犬训练狗狗