首页 > 编程语言 >August 1st, Java Study Notes,static&non-static method

August 1st, Java Study Notes,static&non-static method

时间:2024-08-01 23:53:22浏览次数:26  
标签:non Java weight dog static 静态方法 new public

I followed the video and recorded some of it

Most of the ideas are already in the comments, and to put it bluntly, they are the translated words

public class dog {
    public int weight;
    //dog没有一个固定的weight,所以我们不使用static定义weight
    //定义了一个静态变量binomen,是dog这个类具有的共同具有的属性
    public static String binomen = "普通家犬";// 狗的学名(binomen)

    public dog(int w){
        weight = w;
    }

    public void bark(){
        if (weight > 50){
            System.out.println("小狗 汪!");
        } else {
            System.out.println("大狗 汪汪汪!");
        }
    }

    public static dog compareDog(dog d1, dog d2 ){
        if (d1.weight > d2.weight){
            return d1;
        } else {
            return d2;
        }
    }

    public dog compareDog(dog d2){ //非静态方法
        if (weight > d2.weight){
            return this;
        } else {
            return d2;
        }
    }

    /*
    静态方法和非静态方法
    有时候,一个类中可能会混用静态方法和非静态方法
    一个很好的例子,比如说我要使用 Math类 中的一个方法
    x=Math.round(5.6);
    上面这样写就比下面要更好:
    Math m = new Math();
    x = m.round(5.6)
    是不是?这样的话,在非静态方法中我使用round方法还要去new一个对象,而使用静态方法就可以直接一步到位
    */

    public static void main(String[] args) {
        dog test = new dog(100);
        test.bark();

        System.out.println("狗的学名:" + dog.binomen);
        // ======================分隔=========================

        // 静态(static)方法
        dog wangcai = new dog(30);
        dog dahuang = new dog(70);
        dog stat_larger = dog.compareDog(wangcai, dahuang);
        stat_larger.bark();

        // 非静态(non-static)方法
        dog test_1 = new dog(30);
        dog test_2 = new dog(70);
        dog nstat_larger = test_1.compareDog(test_2);
        nstat_larger.bark();

    }

}

标签:non,Java,weight,dog,static,静态方法,new,public
From: https://blog.csdn.net/Roain_YxY/article/details/140860002

相关文章