java问题,求大神解决

左右之间 2015-03-02 01:38:37
1、怎么调用父类被重写的方法?创建了子类对象,用super.方法名的方式为什么会编译错误?
class Z {
static void f() {
System.out.println("Hello!");
}
}

class B extends Z {
static void f() {
System.out.println("Goodbye!");
}

public static void main(String[] args) {
B bb = new B();
super.f();
}

}
错误:
-------------------------------------------------------------------------------
Z.java:14: 错误: 无法从静态上下文中引用非静态 变量 super
super.f();
^
1 个错误
-------------------------------------------------------------------------------

2、为什么没有结果输出?
代码:
class Computer {
public void turnOn(Computer computer) {

}

public static void main(String[] args) {
Computer computer = new Computer();
computer.turnOn(new PC());
computer.turnOn(new NBC());
}
}

class PC extends Computer {
public void turnOn() {
System.out.println("PC has turn on");
}
}

class NBC extends Computer {
public void turnOn() {
System.out.println("NBC has turn on");
}
}
...全文
171 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wonkju 2015-03-02
  • 打赏
  • 举报
回复
Z z = new B(); z.f(); 编译类型和运行不一致,所以产生多态.当运行的时候, z才知道实际指向的是B类型,所以会调用子类中覆盖的方法.
wonkju 2015-03-02
  • 打赏
  • 举报
回复
你都不理解super是什么意思, 这也太基础了吧. super是父类对象,当然不能用在类方法中.super用法和this一模一样.
寒沙胜雪 2015-03-02
  • 打赏
  • 举报
回复
或者你可以在main函数里面直接用Z.f();
寒沙胜雪 2015-03-02
  • 打赏
  • 举报
回复
Cannot use super in a static context //不能在静态上下文中使用super方法 //也不能用super调用static方法

package test;

class Z {
	 void f() {
		System.out.println("Hello!");
	}
}

class test extends Z {
	void f() {
		System.out.println("Goodbye!");
		super.f();
	}

	public static void main(String[] args) {
		test bb = new test();
		bb.f();
	}

}
uwolf1233 2015-03-02
  • 打赏
  • 举报
回复
大哥,你子类的那个方法没有重写父类的方法,静态方法不能被重写,所以你的子类的那个方法和父类的没有关系,没法super
rumlee 2015-03-02
  • 打赏
  • 举报
回复
super关键字只能在成员方法中调用。 而且如果子类已经重写了父类的某个方法,除了在子类重写的这个方法之外,不应该再调用被重写的那个父类方法。

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧