Boolean second question, Java

Asked 1 years ago, Updated 1 years ago, 51 views

public class TapeDeckTestDrive {

public static void main(String[] args) {

    TapeDeck t = new TapeDeck();

    t.canRecord =true;

    if (t.canRecord == true) {
        t.recordTape();
    }

}

}

class TapeDeck{

boolean canRecord = false;

void playTape() {
    System.out.println("tape playing");
}

void recordTape() {
    System.out.println("tape recording");
}

}

I'm a beginner who feels the boolean price is too difficult.

I don't know why TapeDeck class gave false value to canRecord as boolean value.

In addition, after specifying false, the tapeTestDrive class goes to the object value of t

It's set to true, but I don't know why.

Learning object-oriented programming...

boolean java

2022-09-21 20:15

1 Answers

I don't know why TapeDeck class gave false value to canRecord as boolean value.

=> By default, if you do not give an initialization value, you have false. If you just say boolean can Record;, it sets it to false when compiling. But why did you give false? If you ask, you have to ask the designer.

First, think carefully about the properties (fields) and methods in object orientation.

TapeDeck should include the ability to record on tape. By the way, I would like to turn on the record switch to stop for a while or to prevent a mistake.

Here, the method is a function of re-recording, and whether the record works or not becomes a property.

In other words, the canRecord must be true to be recorded.

In fact, in the example above,

if (t.canRecord == true) {
        t.recordTape();
    }

I did, but I removed it.

void recordTape() {
    if(canRecord)
        System.out.println("tape recording");
}

It's right to do it with.

The canRecord value changes to true when t.canRecord = true;.


2022-09-21 20:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.