当从构造函数调用时,关键字“super”如何工作?

时间:2010-10-28 07:13:00

标签: java

import java.io.*;

class MyException1
{
static String str="";

 public static void main(String args[])
 {
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 System.out.println("Enter your food");


 try{
 str=br.readLine();
 }catch(IOException e){
 System.out.println("Exception has been occurred"+e);
 }


 try{
 checkFood();
 }catch(BadException be){
 System.out.println("Exception"+be);
 }
 }


 private static void checkFood() throws BadException
 {

 if(str.equals("Rotten")|| str.equals("")){
 System.out.println("Bad food");
 //throw new BadException();
 throw new BadException("Not Eatable");
 }else{
 System.out.println("Good food !! enjoy");

 }
 }
}



class BadException extends Exception
{
String food;

 BadException()
 {
 super(); 
 food="invalid";
 System.out.println(food);
 }

 BadException(String s)
 {
 super(s); 
 food=s;
 }

 public String getError()
 {
 return food;
 }

}

在该计划中,public String getError()如何返回food变量?我还没有把它叫到任何地方?

如果删除行super(s);,则不会打印“Not Eatable”。但是,如果我留下那条线,那么它就会打印出来。这个程序流程如何运作?

3 个答案:

答案 0 :(得分:2)

  

如果我删除行super(s);,则“Not Eatable”不会被打印。但是,如果我留下那条线,那么它就会打印出来。这个程序流程如何运作?

super(s)将调用带有字符串的“超类”构造函数。就像你打电话给new Exception("Not Eatable")一样。 Exception的此构造函数向异常添加了一条消息,因此当您将其打印出来时,它将包含该文本。

这与变量food无关。您可以删除行food=s;,但邮件仍会正确打印出来。

请参阅本教程,了解关键字super

http://download.oracle.com/javase/tutorial/java/IandI/super.html

如果你仍然对super如何运作感到困惑,那么请考虑一下。您可以使用此代码重新编码BadException,您的程序仍将执行完全相同的操作:

class BadException extends Exception
{
 BadException(String s)
 {
  super(s);
 }
}

这也会做同样的事情:

class Test extends Throwable
{
 String message;
 Test(String msg)
 {
  message = msg;
 }
 public String toString() {
  return "BadException: " + message;
 }
}

class BadException extends Test
{
 BadException(String s)
 {
  super(s);
 }
}

答案 1 :(得分:1)

当你throw new BadException("not eatable");实例化一个新的BadException时,它将其成员变量food设置为字符串“not eatable”。然后调用getError()将返回该字符串。

摆脱食物成员变量并只调用super(String)会更好的风格,因为有一个构造函数Exception(String message)

答案 2 :(得分:0)

“超级(一个或多个);”调用带有一个String的超类构造函数。那是Exception类。

如果你取出“super(s);”,那么编译器将隐含地放一个“super();”在那里调用,因为超类有一个默认的构造函数。 (这就是为什么它被称为默认构造函数 - 因为如果你没有指定任何其他内容,它将被默认调用!)

由于这与调用“super(null);”相同,因此消息(在变量“s”中)不会传递给超类,因此它不会打印出来..