如何在Java中从另一个类访问变量?

huangapple go评论74阅读模式
英文:

How do I access variables from another class in Java?

问题

我有一个名为Customer的类,其中customerName、customerEmail和customerAddress是在名为a的对象中设置的变量。我该如何在另一个名为BookingConfirmation的类中打印变量customerName、customerEmail和customerAddress?我尝试过:

System.out.println("Thanks for your booking " + a.getCustomerName());

以下是Customer类的代码:

public class Customer {

    String customerName;
    String customerEmail;
    String customerAddress;

    public static void customerDetails() throws IOException {

        Customer a = new Customer();

        Scanner seekName = new Scanner(System.in);
        System.out.print("Your name: ");
        a.customerName = seekName.nextLine();

        Scanner seekEmail = new Scanner(System.in);
        System.out.print("Your email: ");
        a.customerEmail = seekEmail.nextLine();

        Scanner seekAddress = new Scanner(System.in);
        System.out.print("Your residential address: ");
        a.customerAddress = seekAddress.nextLine();

        System.out.println("Thanks for your booking " + a.getCustomerName());
        System.out.println("Eemail: " + a.getCustomerEmail());
        System.out.println("Address: " + a.getCustomerAddress());
        System.out.println();
    }

    public String getCustomerName() {
        return customerName;
    }

    public String getCustomerEmail() {
        return customerEmail;
    }

    public String getCustomerAddress() {
        return customerAddress;
    }

}
英文:

I have a class called Customer with customerName, customerEmail and customerAddress as variables set in an object called a. How do I print the variables customerName, customerEmail and customerAddress in another class called BookingConfirmation? I tried:

System.out.println("Thanks for your booking " + a.getCustomerName());

Here is the code for Customer class:

public class Customer {

String customerName;
String customerEmail;
String customerAddress;
    
    public static void customerDetails() throws IOException {
        
        Customer a = new Customer();
    
        Scanner seekName = new Scanner(System.in);  // Create a Scanner object
        System.out.print("Your name: ");
        a.customerName = seekName.nextLine();  // Read user input
            
        Scanner seekEmail = new Scanner(System.in);  // Create a Scanner object
        System.out.print("Your email: ");
        a.customerEmail = seekEmail.nextLine();  // Read user input
            
        Scanner seekAddress = new Scanner(System.in);  // Create a Scanner object
        System.out.print("Your residential address: ");
        a.customerAddress = seekAddress.nextLine();  // Read user input
        

        System.out.println("Thanks for your booking " + a.getCustomerName());
        System.out.println("Eemail: " + a.getCustomerEmail());
        System.out.println("Address: " + a.getCustomerAddress());
        System.out.println();
    }
    
        public String getCustomerName() {
            return customerName;
        }
        
        public String getCustomerEmail() {
            return customerEmail;
        }
                
        public String getCustomerAddress() {
            return customerAddress;
        }
                
}

答案1

得分: 2

不确定我是否明白您的问题,但似乎您可以执行以下操作:

1)使customerDetails()方法将a(创建的Customer对象)作为该方法的结果返回。

2)从BookingConfirmation中调用Customer.customerDetails(),并将返回的值保存在一个名为Customer a的局部变量中。

3)然后您可以在BookingConfirmation代码内部调用System.out.println("Thanks for your booking " + a.getCustomerName());

英文:

I'm not sure I know what you're asking, but it seems that you could do the following:

  1. Have the customerDetails() method return a (the created Customer object) as the result of the method.

  2. Call Customer.customerDetails() from BookingConfirmation, and save returned value in a local variable Customer a.

  3. Then you can call System.out.println("Thanks for your booking " + a.getCustomerName()); inside the BookingConfirmation code.

答案2

得分: 0

如果您只想从类的外部访问属性的值,那么您需要为每个要检索的属性创建getter方法。

如果您想要从类的外部修改这些值,您需要创建一个setter方法。

Getter和Setter只是允许您在类外部访问类的属性的方法。

如果您有一个名为Customer的类,并且想要从外部访问和修改它的名称,您需要创建2个方法,

//声明属性
private String name;

//getter
public String getName(){
   return this.name;
}

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

//然后您可以在任何其他地方实例化一个Customer对象,并访问这些属性

Customer cust = new Customer();
cust.setName("Mark");
System.out.println("Oh hi " + cust.getName());
//输出 "Oh hi Mark"

阅读更多关于getter和setter

此外,最佳实践提示:实例变量应始终声明为private以帮助封装。如果在Java中未为实例变量提供访问修饰符,则默认为default修饰符,这使得该变量对于同一包中的每个类都是可访问的。

编辑:

您的特定错误是在customerDetails方法内创建了一个新的Customer对象,但未返回此Customer对象。因此,一旦方法被执行,您在内部创建的Customer对象就会被销毁(从内存中清除,垃圾回收),因为没有进一步的引用。

您可以选择:

方法1:将customerDetails方法的返回类型从void更改为Customer,并在结尾处添加return a语句,然后您只需从预订类中实例化一个Customer对象,像这样:

public Customer customerDetails(){               
    Customer a = new Customer();           
    //设置所有属性的逻辑          
    return a;        
}

在您的预订类中

Customer myCust = new Customer();
myCust = myCust.customerDetails();

我不太喜欢这种方法,因为正如您所看到的,您只是创建了一个空对象,然后重新分配给它。或者您可以在public之后添加static关键字,这样您就可以在没有实例化类的对象的情况下调用它,如下所示:

预订类

Customer myCust = Customer.customerDetails();

方法2:从customerDetails中删除Customer a = new Customer(),并且只需使用this.name = sc.nextLine()来设置调用此方法的实例的名称。

然后在预订类中,实例化一个新的Customer对象并调用该方法。

Customer myCust = new Customer();
myCust.customerDetails();
英文:

If you simply want to access the value of a property from outside of the class, then you need to create getters for each one of the properties you want to retrieve.

If you want to modify these values from outside of the class, you need to create a setter.

Getters and Setters are simply methods that allow you to access properties of a class outside of it.

If you have the class Customer and want to access and change it's name from outside, you'd create 2 methods,

//declare the property
private String name;

//getter
public String getName(){
   return this.name;
}

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

//You can then instantiate a Customer object anywhere else and have access to those //properties

Customer cust = new Customer();
cust.setName("Mark")
System.out.println("Oh hi " + cust.getName());
//output "Oh hi Mark"

Read more on getters and setters

Also, best practices tip: instance variables should always be declared as private to help encapsulation. If no access modifier is provided for an instance variable in Java, it defaults to the default modifier, which makes the variable accessible for every class within the same package.

Edit:

Your specific error is that you are creating a new Customer object within your customerDetails method, and you're not returning this Customer object. Therefore, as soon as the method has been executed, the Customer object you created inside is destroyed (cleared from memory,Garbage collected), because there is no further reference to it.

You either need to

Method 1: Change the return type of your customerDetails method from void to Customer and add a return a statement at the end, then you would simply need to instantiate a Customer object from your booking class, like so

public Customer customerDetails(){               
    Customer a = new Customer();           
    //your logic to set all of the properties          
    return a;        
}

in your booking class

Customer myCust = new Customer();
myCust = myCust.customerDetails();

I would not prefer this method, because as you see, you're just creating an empty object then reassigning to it. You may alternatively add the static keyword after public so that you can call it without having instantiated an object of the class, like so

booking class

Customer myCust = Customer.customerDetails();

Method 2: remove the Customer a = new Customer() from the customerDetails altogether and simply use this.name = sc.nextLine() to set the name of whatever instance is calling this method.

Then on bookings class, instantiate a new Customer object and call the method.

Customer myCust = new Customer();
myCust.customerDetails();

huangapple
  • 本文由 发表于 2020年9月13日 10:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63866702.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定