JAVA的三种给对象赋值的方式

  • 第一种,直接赋值的方式
package Experience;

public class Teacher {
    String name;
    int age;
    public void act(){
        System.out.println("大家好,我是田老师!");
    }
}


package Experience;

public class Test {
    public static void main(String[] args){
        Teacher teacher=new Teacher();
        teacher.name="田老师";
        teacher.age=35;
        System.out.println("今天"+teacher.age+"岁的"+teacher.name+"要来给我们上课!");
        teacher.act();
    }
}

  • 第二种,private封装使用方法赋值
package Experience;
public class Student {
   private String name;
   private int age;
    public void show(){
        System.out.println(name+","+age);
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public  void setAge(int age){
        if(age<=0){
            System.out.println("年龄错误");
        }else{
            this.age=age;
        }
    }

    public int getAge() {
        return age;
    }
}


package Experience;

public class Learn02 {
    public static void main(String[] args){
        Student s=new Student();
        s.setName("小红");
        s.setAge(24);
        s.show();
        System.out.println(s.getName()+"今年多少岁了:"+s.getAge());

    }
}


  • 第三种,使用构造方法的方式
package Experience;

public class Test {
    public static void main(String[] args){
        Teacher teacher=new Teacher("田老师",35);
        System.out.println("今天"+teacher.getAge()+"岁的"+teacher.getName()+"要来给我们上课!");
        teacher.act();
    }
}


package Experience;

public class Teacher {
   private String name;
   private int age;
   Teacher(String name,int age){
       this.name=name;
       this.age=age;
       System.out.println("同学们好!");
   }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void act(){
        System.out.println("大家好,我是田老师!");
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值