初始化对象变量错误(Initialize object variable error)
编译以下代码时出错:
class TapeDeck { boolean canRecord = false; void playTape() { System.out.println("tape playing"); } void recordTape() { System.out.println("tape recording"); } } class TapeDeckTestDrive { public static void main(String [] args) { TapeDeck t; t.canRecord = true; t.playTape(); if(t.canRecord == true) { t.recordTape(); } } }错误是:
TapeDeck.java:21: error: variable t might not have been initialized t.canRecord = true; ^ 1 error如何在类中初始化变量t ?
I got an error compiling the following code:
class TapeDeck { boolean canRecord = false; void playTape() { System.out.println("tape playing"); } void recordTape() { System.out.println("tape recording"); } } class TapeDeckTestDrive { public static void main(String [] args) { TapeDeck t; t.canRecord = true; t.playTape(); if(t.canRecord == true) { t.recordTape(); } } }The error is:
TapeDeck.java:21: error: variable t might not have been initialized t.canRecord = true; ^ 1 errorHow shall I initialize the variable t in the class?
最满意答案
使用new关键字初始化对象。
TapeDeck t = new TapeDeck();Use new keyword to initialize objects.
TapeDeck t = new TapeDeck();更多推荐
发布评论