A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 毕影彬 中级黑马   /  2012-10-28 22:30  /  1568 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 毕影彬 于 2012-10-29 18:21 编辑

、下面2个文件位于相同目录下,编译运行后会出现的情况是( )。  
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
  System.out.println("What a fancy method");
  }
}
//File P2.java
public class P2 extends P1{
  public static void main(String argv[]){
P2 p2 = new P2();
p2.afancymethod();
  }
}
A、2个文件都可以编译,P2运行输出“What a fancy method”
B、2个文件都不能编译  
C、2个文件都可以编译,P2运行时报错误  
D、P1编译成功,P2编译时报错误  
选哪个呢?为什么?请说的详细点,谢谢

7 个回复

倒序浏览
本帖最后由 种生祥 于 2012-10-28 22:47 编辑

没有选项
P1.java编译错误
public class P2 extends P1//public去掉之后可以成功,因为带main的类前面如果有public的话,必须保存为该类名.java
P2.java编译成功
p2.afancymethod();//子类对象调用子类从父类继承的afancymethod()方法
就是这样啊
回复 使用道具 举报
选D,P2.java编译时找不到P1类,因为虽然在同一个文件夹下,但P1类打包了,其类的全名应是mypackage.P1。
回复 使用道具 举报
我觉得吧 应该选择D ,因为在主函数中通过P2的对象调用的,并且P2对象调用子类从父类继承的afancymethod()方法。
回复 使用道具 举报
选择D ,P2无访问P1,因为P2继承P1属于子类继承父类,应位于P1的子目录中

搜狗截图_2012-10-29_00-18-04.png (5.05 KB, 下载次数: 21)

搜狗截图_2012-10-29_00-18-04.png
回复 使用道具 举报
选择D , 因为P2不能够找到P1,用public,private等限定一下就可以了 p2.afancymethod();p2找不到这个方法
回复 使用道具 举报
看JDK的版本了,1.4之前是可以编译的。官方给出的说明:
The compiler now rejects import statements that import a type from the unnamed namespace. Previous versions of the compiler would accept such import declarations, even though they were arguably not allowed by the language (because the type name appearing in the import clause is not in scope). The specification is being clarified to state clearly that you cannot have a simple name in an import statement, nor can you import from the unnamed namespace.
回复 使用道具 举报
我试了下,结果是A
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马