1 Replies - 556 Views - Last Post: 01 May 2009 - 08:58 AM Rate Topic: -----

#1 ryan5554  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 10-April 09

Calling methods from other files

Post icon  Posted 01 May 2009 - 08:45 AM

Hey everyone

I'm currently working on a project that requires me to call methods from other files and I'm not quite sure how

I have 3 files:

1: is a driver program that contains the main() method it declares and instantiates an object of the second file (number 2) and calls 2 of the methods within inside it along with the main method.

2: This file contains the bulk of the resources I'm going to use to implement my program

3: This is where I build the program using the methods from the other 2

What I'm unsure of:

Am I supposed to use something to call these methods into program 3 or just copy them into it or link these files together somehow because how it stands at the moment is I put all the files into the one folder and just tried some println's seeing if the main() method automatically called due them being in the same folder but nope.

So yeah question is how do I get them from files 1 and 2 into file 3

Is This A Good Question/Topic? 0
  • +

Replies To: Calling methods from other files

#2 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Calling methods from other files

Posted 01 May 2009 - 08:58 AM

Ok, here is an example of a Shopping Class. It is very short only for Example
Item.java
public class Item
{
public Item(double price, String name)
	 {
		 this.price = price; this.name = name;
	 }
public String getName(){return name;}
public double getPrice(){return price;}
}

ShoppingCart.java
public class ShoppingCart
{
ArrayList<Item> cart = new ArrayList<Item>(); // Creates an arraylist of an instance of an Item. (An arraylist of item objects)
public void add(Item a){cart.add(a);}
public String toString()
{String out = "";
for(Item a : cart) // for each loop of the object item
	  out += a.getName() + "\n" + a.getPrice() + "\n"; // Because the arraylist is an arraylist of item objects, you can access th methods in the Item class
return out;
}
}


and now, Shop.java
//Create an shopping cart object
// Printed menu with a switch statement to option 1, add item.
case 1 : // get a name and price
			  objectName.add(theItem); // You make a shoppingcart object int his class, gives you access to that classes methods, which can get to Items methods. You invoke the add method of ShoppingCart Class.



Hope this helps!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1