简体   繁体   English

如何调用 class object 作为方法参数

[英]how do I call class object as a method parameter

I have 3 classes, one is Account, one is Bank and one is Main.我有 3 个类,一个是 Account,一个是 Bank,一个是 Main。 In the bank class I have a method在银行 class 我有一个方法

public boolean addAccount(Account account){
return false;}

I have some code in this method, my question is how do I call this method from the class with the main method???我在这个方法中有一些代码,我的问题是如何从 class 中调用这个方法与 main 方法??? My parameter is the class but it is from another class I can't find an example of this.我的参数是 class 但它来自另一个 class 我找不到这样的例子。

I have tried creating an object but it does not work for example if I do我尝试创建一个 object 但它不起作用,例如,如果我这样做

Account someObject = new Account(); or
Bank someObject = new Bank(); 

it is not going to allow me to access both classes right?它不会允许我访问这两个类吗? Sorry I just don't get it...对不起,我只是不明白...

The point of this is to add a new account and later on with a different method check the account.这样做的目的是添加一个新帐户,然后使用不同的方法检查该帐户。 I already have some account objects with the name of account, the number of the account and the balance.我已经有一些具有帐户名称、帐户编号和余额的帐户对象。 Any help clarifying this would be greatly appreciated.任何澄清这一点的帮助将不胜感激。

Hope this example will help:希望这个例子会有所帮助:

class ObjectPassDemo 
{ 
    int a, b; 

    ObjectPassDemo(int i, int j) 
    { 
        a = i; 
        b = j; 
    } 


    boolean equalTo(ObjectPassDemo o) 
    { 
        return (o.a == a && o.b == b); 
    } 
} 


public class Test 
{ 
    public static void main(String args[]) 
    { 
        ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); 
        ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); 
        ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1); 

        System.out.println("ob1 == ob2: " + ob1.equalTo(ob2)); 
        System.out.println("ob1 == ob3: " + ob1.equalTo(ob3)); 
    } 
}

Ref: https://www.geeksforgeeks.org参考: https://www.geeksforgeeks.org

You call such a method with the syntax:您可以使用以下语法调用此类方法:

someBankObject.addAccount(someAccountObject);

Depending on the code you already have it might look like this:根据您已经拥有的代码,它可能如下所示:

Account johnDoeAccount = new Account("John", "Doe", "JD-423-127-231"); // example
Bank centralBank = new Bank();
centralBank.addAccount(johnDoeAccount);

Now your account variable inside your addAccount() method will reference the account from John Doe.现在,您的addAccount()方法中的account变量将引用来自 John Doe 的帐户。

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

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