簡體   English   中英

從構造函數中調用時,關鍵字“ super”如何工作?

[英]How does the keyword “super” work, when called from a constructor?

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);super(s); ,則不會打印“不可食用”。 但是,如果我將該行留在里面,那么它的確會打印出來。 該程序流程如何工作?

如果刪除行超級;則不會打印“不可食用”。 但是,如果我將該行留在里面,那么它的確會打印出來。 該程序流程如何工作?

super(s)將調用采用字符串的“ super class”構造函數。 就像您調用過new Exception("Not Eatable") Exception構造函數會向該Exception添加一條消息,因此當您將其打印出來時,它將包含該文本。

這與food種類無關。 您可以刪除food=s;這一行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);
 }
}

當您throw new BadException("not eatable"); 您正在實例化一個新的BadException,它將其成員變量food設置為字符串“ not eatable”。 然后,對getError()的調用將返回該字符串。

最好刪除食物成員變量,然后調用super(String),因為有構造函數Exception(String message)

“超級”;” 調用采用一個String的超類的構造函數。 那是Exception類。

如果您刪除“ super(s);”,則編譯器將隱式放置“ super();”。 在那里調用,因為超類具有默認構造函數。 (這就是為什么它被稱為默認構造函數的原因-因為如果您不指定其他任何內容,它將在默認情況下被調用!)

由於這與調用“ super(null);”相同,因此消息(位於變量“ s”中)不會傳遞給超類,因此該消息無法打印出來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM