Skip to content
Advertisement

How do I pass class objects as parameters in a method? [closed]

I am new to Java. I have a Fruit class (name and price are my instance variables) and FruitBasket (3 instance variable of Fruit f1, f2, f3).

I am trying to create a swap method that takes 3 Fruit objects as parameters. Please provide me with a a simple answer as this is an assignment.

Advertisement

Answer

Passing an object as a parameter is a lot like passing any other parameter. You just need to use the name of the object class, in your case Fruit, in place of any other variable type.

It’s also a lot like how you would define the instance variables of type Fruit in your FruitBasket class.

For example, if you have a method signature like so:

public void swap(int f1, int f2){}

You can just replace the keyword int with the keyword Fruit or whatever your object class name is.

public void swap(Fruit f1, Fruit f2, Fruit f3){}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement