我们可以覆盖Java中的私有方法还是静态方法
不可以,我们不能覆盖Java中的私有或静态方法。
Java中的私有方法对任何其他类都不可见,从而将其范围限制在声明它们的类中。
示例
让我们看看尝试覆盖私有方法时会发生什么-
class Parent {
private void display() {
System.out.println("Super class");
}
}
public class Example extends Parent {
void display() // trying to override display() {
System.out.println("Sub class");
}
public static void main(String[] args) {
Parent obj = new Example();
obj.display();
}
}输出结果
输出如下-
Example.java:17: error: display() has private access in Parent
obj.method();
^
1 error该程序给出一个编译时错误,表明display()在Parent类中具有私有访问权限,因此不能在Example类的子类中覆盖它。
如果方法声明为静态,则它是类的成员,而不是属于该类的对象。可以在不创建该类的对象的情况下调用它。静态方法还具有访问类的静态数据成员的能力。
示例
让我们看看尝试覆盖子类中的静态方法时会发生什么
class Parent {
static void display() {
System.out.println("Super class");
}
}
public class Example extends Parent {
void display() // trying to override display() {
System.out.println("Sub class");
}
public static void main(String[] args) {
Parent obj = new Example();
obj.display();
}
}输出结果
这将产生一个编译时错误。输出如下-
Example.java:10: error: display() in Example cannot override display() in Parent void display() // trying to override display() ^ overridden method is static 1 error
热门推荐
10 文艺乔迁祝福语简短精辟
11 恭喜高考完祝福语简短
12 关于长辈祝福语大全简短
13 高考祝福语歌词文案简短
14 送给老街的祝福语简短
15 同事调动祝福语 简短独特
16 演讲生意祝福语大全简短
17 祝福语女生生日简短
18 药店五一祝福语简短幽默