初始化对象变量错误(Initialize object variable error)

编程入门 行业动态 更新时间:2024-10-11 09:27:13
初始化对象变量错误(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 error

How shall I initialize the variable t in the class?

最满意答案

使用new关键字初始化对象。

TapeDeck t = new TapeDeck();

Use new keyword to initialize objects.

TapeDeck t = new TapeDeck();

更多推荐

本文发布于:2023-04-29 03:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   变量   对象   错误   variable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!