首页 > 其他 > 详细

构造方法

时间:2020-02-17 21:50:25      阅读:74      评论:0      收藏:0      [点我收藏+]
package com.lv.test;

public class Cat {
    
    String name;
    int  age;
    
    public Cat(){
        
    }
    //带参数的构造器
    public Cat(String name){
        this.name =name;
    }
    
    public Cat(String name,int age){
        this(name);//不要加构造器cat名字
    }
    public void say(){
        //我的需求是  想要jack喵喵
        //想要使用当前对象的name 而不是这个局部变量的name
        
        String name="tom";
        //this 关键字代表当前对象
        //System.out.println(this.name+"喵喵喵");
        System.out.println(this.name+"喵喵喵");
    }
    
    public static void main(String[] args) {
        Cat cat1=new Cat();
        cat1.say();//为啥是null喵喵 因为String name;没有赋值
        
        Cat cat2=new Cat("jerry");
        cat2.say();
        
        Cat cat3=new Cat("tony");
        cat3.say();
    }
}

技术分享图片

 

 技术分享图片

 

 技术分享图片

 

构造方法

原文:https://www.cnblogs.com/dabu/p/12323475.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!