I'm curious about the use of boolean in Java.

Asked 2 years ago, Updated 2 years ago, 118 views

public class DrumKitTestDrive {

public static void main(String[] args) {
    DrumKit d = new DrumKit();
    d.playSnare();
    d.playSnare = false;

    d.playTopHat();

}

}

class DrumKit{

boolean topHat = true;
boolean playSnare = true;

void playSnare() {
    System.out.println("bang bang ba-bang");
    }

void playTopHat() {
    System.out.println("ding ding da-ding");
    }

}

I don't understand the lines with boolean in the code above.

I don't know why I use it and just say boolean has a true, false value

I learned it. Is that right?

d.playSnare = false; << This part requires an object called d to execute the method called playSnare

What's the difference between words? And I don't know why I have a false value.

boolean

2022-09-21 15:21

2 Answers

I think it's a code to show the difference between the field of the same name and the method.

The DrumKit class has two methods: the boolean playSnare field and the void playSnare().

d.playSnare = false;

The above code uses the field boolan playSnare and

d.playSnare();

will use the method voidplaySnare().

I think I wanted to explain that depending on whether the operator you use in this way is = or (), the field or method that you access even if it is the same name.

I don't think true and false have any meaning.

Note that for C++, compilation errors can occur when methods and fields have the same name.


2022-09-21 15:21

Properties and methods are different.

Properties represent properties for that object, and methods represent actions.

For example, if it's an object called a car...Color, displacement, etc. become properties, and methods such as forward, backward, etc.

Unlike modern languages, Java is a must. Point to the field if there is no () and method if there is ().

I don't know what explanation the example was given in the question, but it seems to be lacking in object-oriented terms.

I think it should be designed as below.

class DrumKit{

    //boolean topHat = true;            
    Private boolean is TopHat = true; // Encapsulation. TopHat Existence
    //boolean playSnare = true;
    Private boolean isPlaySnare = true; // Snare playability

    public void playSnare() {
        If(isPlaySnare) // If true, do it
            System.out.println("bang bang ba-bang");
    }

    public void playTopHat() {
        if(isTopHat)
            System.out.println("ding ding da-ding");
    }

    public void setIsTopHat(boolean value){
        isTopHat = value;
    }
    public boolean getIsTopHat (){
        return isTopHat;
    }

    public void setIsPlaySnare(boolean value){
        isPlaySnare= value;
    }
    public boolean getIsPlaySnare (){
        return isPlaySnare; 
    }

}


2022-09-21 15:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.