evan harijanto
evan harijanto

Reputation: 13

using 1 variables in different constructor in java

@Override
public void onIrEvent(IREvent e) {
    // TODO Auto-generated method stub

}


ardrone.addAttitudeUpdateListener(new AttitudeListener() {
        @Override
        public void attitudeUpdated(float pitch, float roll, float yaw, int altitude) {
        System.out.println("altitude : " + altitude);
        }
    });

i want to take the variables altitude from the second constructor and use it in the first constructor. I tried to use it directly and it didnt work. I also tried to construct the 2nd constructor inside the 1st one, but also didn't work. any idea?

thanks before

Upvotes: 0

Views: 58

Answers (2)

codeMan
codeMan

Reputation: 5758

create a new class that implements AttitudeListener. Have a instance variable altitude with setter and getter method for the altitude and use it accordingly in your first and second constructor.

Example : in AttitudeListenerImpl.java

class AttitudeListenerImpl implements AttitudeListener
{
    private int altitude;
    public void setAltitude(int altitude)
    {
        this.altitude = altitude;
    }
    public int getAltitude()
    {
        return this.altitude;
    }
    @Override
    public void attitudeUpdated(float pitch, float roll, float yaw, int altitude) 
    {
        setAltitude(altitude);
        System.out.println("altitude : " + altitude);
    }
}

Usage in your other code:

AttitudeListener alti = new AttitudeListenerImpl();
alti.attitudeUpdated(1.0f,1.0f,1.0f,1);
ardrone.addAttitudeUpdateListener(alti);

@Override
public void onIrEvent(IREvent e) 
{
        // TODO Auto-generated method stub
        //to get the altitude:
         System.out.println("altitude : " + alti.getAltitude()); 

}

Upvotes: 1

Atmocreations
Atmocreations

Reputation: 10071

I don't see any constructor here. Are you talking about AttitudeListener? In this case, you would need to create a class implementing this interface.

What you could do then is constructor chaining, like for example:

public class MyAttitudeListener implements AttitudeListener
{
    public MyAttitudeListener()
    {
        this(3); // this is like new MyAttitudeListener(3);
    }
    public MyAttitudeListener(int altitude)
    {
        // do some work
    }        
}

Could you explain further what goal you're trying to achieve?

Upvotes: 0

Related Questions