简体   繁体   English

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

[英]How do I access variables from another class in Java?

I have a class called Customer with customerName, customerEmail and customerAddress as variables set in an object called a.我有一个名为 Customer 的类,其中 customerName、customerEmail 和 customerAddress 作为变量设置在名为 a 的对象中。 How do I print the variables customerName, customerEmail and customerAddress in another class called BookingConfirmation?如何在另一个名为 BookingConfirmation 的类中打印变量 customerName、customerEmail 和 customerAddress? I tried:我试过:

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

Here is the code for Customer class:这是 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);  // 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;
        }
                
}

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.customerDetails()方法返回a (创建的 Customer 对象)作为该方法的结果。

  2. Call Customer.customerDetails() from BookingConfirmation , and save returned value in a local variable Customer a .BookingConfirmation调用Customer.customerDetails() ,并将返回值保存在局部变量Customer a

  3. Then you can call System.out.println("Thanks for your booking " + a.getCustomerName());然后你可以调用System.out.println("Thanks for your booking " + a.getCustomerName()); inside the BookingConfirmation code.BookingConfirmation代码中。

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.如果您只是想从类的外部访问属性的值,那么您需要为要检索的每个属性创建 getter。

If you want to modify these values from outside of the class, you need to create a setter.如果要从类外部修改这些值,则需要创建一个 setter。

Getters and Setters are simply methods that allow you to access properties of a class outside of it. Getters 和 Setters 只是允许您访问类外部属性的简单方法。

If you have the class Customer and want to access and change it's name from outside, you'd create 2 methods,如果您有类Customer并想从外部访问和更改它的名称,您将创建 2 个方法,

//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阅读有关getter 和 setter 的更多信息

Also, best practices tip: instance variables should always be declared as private to help encapsulation.此外,最佳实践提示:实例变量应始终声明为private以帮助封装。 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.如果在 Java 中没有为实例变量提供访问修饰符,则默认为default修饰符,这使得同一包中的每个类都可以访问该变量。

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.您的具体错误是您在customerDetails方法中创建了一个新的Customer对象,并且您没有返回这个Customer对象。 Therefore, as soon as the method has been executed, the Customer object you created inside is destroyed, because there is no further reference to it.因此,一旦执行了该方法,您在其中创建的Customer对象就会被销毁,因为没有进一步引用它。

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方法 1:将 customerDetails 方法的返回类型从void更改为Customer并在最后添加return a语句,然后您只需从预订类中实例化 Customer 对象,如下所示

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您也可以在public之后添加static关键字,这样您就可以在不实例化类的对象的情况下调用它,就像这样

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.方法 2:从 customerDetails 中完全删除Customer a = new Customer()并简单地使用this.name = sc.nextLine()来设置调用此方法的任何实例的名称。

Then on bookings class, instantiate a new Customer object and call the method.然后在预订类上,实例化一个新的 Customer 对象并调用该方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM