美文网首页
二、Java初级--7、setter和getter

二、Java初级--7、setter和getter

作者: cybeyond | 来源:发表于2018-03-06 14:42 被阅读0次

    加注释:“ctrl+/”,取消也是“ctrl+/”

    this代表当前对象,谁来调用,谁就是此时的this


    结构
    package javastudy;
    
    public class Person {
        private String name;
        private int height;
        //setter
        public void setName(String name){
            this.name=name;  //实例对象z来调用setName,此时this即为z;实例对象w调用,this即为w
            
        }
        public void setHeight(int height){
            this.height=height;
        }
        //getter
        public String getName(){
            return name;
        }
        public int getHeight(){
            return height;
        }
    }
    
    
    package javastudy;
    
    public class testit {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    //      z.name="zhang";
    //      z.height=120;
            Person z=new Person();
            z.setName("zhang");
            z.setHeight(170);
            System.out.println(z.getName());
            System.out.println(z.getHeight());
            
            Person w=new Person();
            w.setName("wang");
            w.setHeight(200);
            System.out.println(w.getName());
            System.out.println(w.getHeight());
        }
    }
    
    执行结果

    相关文章

      网友评论

          本文标题:二、Java初级--7、setter和getter

          本文链接:https://www.haomeiwen.com/subject/nqmhfftx.html