-5

How can I call a method from another class?

  public class BankAccount {
        String firstName, lastName;
        double balance;

        BankAccount(String firstName, String lastName,double openingBalance){

        }
        public String getFirstName(){
            return firstName;
        }

        public String getLastName(){
            return lastName;
        }

        public double getBalance(){
            return balance;
        }   
    }

This is my driver class below.. I need a help to call a method from this class.

public class Driver {

    static BankAccount acc1;

    public static void main (String[] args){

        acc1 = new BankAccount ("Tiger","Woods", 200);

    }
}
user3583640
  • 3
  • 1
  • 6

4 Answers4

1

Just do this:

acc1.getFirstName();
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
1

Very simple, your object is called "acc1". To call a method simply type acc1.(and a list of assosiated method will appear) and select whichever one you after.

Eg. If you wanted to get the first name, you could type, acc1.getFirstName(); obviosuly this would do nothing until you put in it a System.out.println(); statement or handle however else you may like to.

Hope this helped, Luke.

Edit - Also noticed your Constructor is not assigning the variables you passed to it. Change your constructor to make it look like this:

BankAccount(String firstName, String lastName,double openingBalance){
          this.firstName = fisrtName;
          this.lastName = lastName;
          this.balance = openingBalance;
        }

What this does is, It tells you class to assign the varibles you passed(the one in teh brackets) to the class varibles(the varibles at the top of the page, which are known as data attributes or class instances).

Again hope this helps. :)

LukeLad
  • 36
  • 3
0

Your contructor has to be like this as it need to initialize variables String firstName, String lastName,double balance you have declared.

public BankAccount(String firstName, String lastName,double openingBalance){
this.firstName=firstName;
this.lastName=lastName;
balance=openingBalance;
}

than

public static void main (String[] args){ 
       BankAccount  acc1 = new BankAccount ("Tiger","Woods", 200);
       System.out.println(acc1.getFirstName());
    }
akash
  • 22,664
  • 11
  • 59
  • 87
  • Thanks for your help, but I still get an error. Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:13) – user3583640 May 06 '14 at 04:12
  • what's there at line no 13 in your driver class as your question don't contain 13 line code for Driver class. – akash May 06 '14 at 04:15
0

You are passing the parameters in your constructor.But you are not assigning them to your local variables.So first assign the values in your BankAccount class constructor and then call the getters to get the values.

Gundamaiah
  • 780
  • 2
  • 6
  • 30