Let's say i have 2 constructor classes; Person and Arm.
public class Person
{
private Arm arm; //instance variable
public Person(Arm arm) //Constructor
{
this.arm = arm;
}
}
-
public class Arm
{
private int fingers; //instance variable
public Arm(int fingers) //Constructor
{
this.fingers = fingers;
}
public int getFingers()
{
return this.fingers();
}
}
Every Person object has an Arm Object as an instance-variable.
Every Arm object has an int instance-variable called fingers.
What is the proper way to access the fingers variable?
1. Create another getFingers() method, in the Person class:
//in Person.java
public int getFingers()
{
return this.arm.getFingers(); //This is refrencing the getFingers() method in the Arm class
}
So i can access it like this:
Arm myArm = new Arm(5);
Person me = new Person(myArm);
System.out.println(me.getFingers());
Create a method in Person that returns the arm.
public Arm getArm() { return this.arm; }
so i can use the getFingers method from the Arm class like this:
Arm myArm = new Arm(5);
Person me = new Person(myArm);
System.out.println(me.getArm().getFingers())
PrivateandPublicwith a capital 'P' are not proper Java keywords.me.getArm().getFingers(), notme.myArm.getFingers()