java类和对象——变量赋值方法

2022-10-26 14:23:41 浏览数 (2)

方法一

代码语言:javascript复制
class Text{
    public String name;
    public int age;
    public int number;
    public void show(){
        System.out.println("姓名:" name " 年龄:" age  " 学号:" number);
    }
}
public class Homework {
    public static void main(String[] args) {
        Text p1 = new Text();
        p1.name = "cathy";
        p1.age = 10;
        p1.number = 20180406;
        p1.show();

方法二

代码语言:javascript复制
class Text{
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
 }
public class Homework {
    public static void main(String[] args) {
        //第二种赋值方法
        Text p2 = new Text();
        p2.setName("dongdong");
        System.out.println(p2.getName());
        p2.setAge(20);
        System.out.println(p2.getAge());
        p2.setNumber(20180304);
        System.out.println(p2.getNumber());

此处的set和get的方法可以用 atl insert 选择Getter and Setting实现

方法三

代码语言:javascript复制
class Text{ 
  Text(){
    }
    Text(String name,int age,int number){
        this.name = name;
        this.age = age;
        this.number = number;
        System.out.println("姓名:" name " 年龄:" age  " 学号:" number);
    }
}
public class Homework {
    public static void main(String[] args) {
       Text p3 = new Text("bobi",50,20180302);
}

0 人点赞