"new Parameters" 在 Java

"new Parameters" on Java

我想要的输出是这样的:

Conan is NOT the same age as Natsu

此输出程序创建最新参数。

Natsu is the same age as Natsu.

下面是我制作的java程序。

Syntax code that I have made

package rawrandomtest;
public class GetSet002 {
    private static String name;
    private static int age;
    public GetSet002(String s, int i){
        GetSet002.name = s;
        GetSet002.age = i;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
    public void setAge(int x){
        GetSet002.age =x;
    }
}

Driver Code

package rawrandomtest;
import java.util.Scanner;
public class GetSet002Driver {
    public static Scanner input = new Scanner (System.in);
    public static void main (String[] args){
        GetSet002 p1 = new GetSet002("Conan", 14);
        GetSet002 p2 = new GetSet002("Natsu", 18);
        if(p1.getAge()==p2.getAge()){
            System.out.println(p1.getName()+" is the same age as "+p2.getName());
        }else{
            System.out.println(p1.getName()+" is NOT the same age as "+p2.getName());
        }
    }
}

年龄是静态变量。每次设置变量时,您都会更改 all 个实例的值。

GetSet002 p1 = new GetSet002("Conan", 14);
//result: GetSet002 = ("Conan" , 14)
GetSet002 p2 = new GetSet002("Natsu", 18);
//result: GetSet = ("Natsu" , 18);

if(p1.getAge() == p2.getAge())
//is semantically equal to:
if(GetSet002.age == GetSet002.age)
//public accessiblity is only implied for demonstration