Jose Miguel Ledón
Jose Miguel Ledón

Reputation: 309

is possible to avoid declaring an object as final?

I'm adding a ChangeListener to a JTabbedPane in the constructor of a JFrame. Inside the stateChanged method I have a method with a parameter that I receive in the constructor, but it need to be final. Is it possible to avoid this?

 public PerfilPaciente(int operation, Patient patient) {
 tabPane.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            switch (tabPane.getSelectedIndex()) {
                case 1:
                    loadDates(patient);   // here is the problem
                    break;
            }
        }
    });

Upvotes: 2

Views: 107

Answers (4)

theme
theme

Reputation: 361

There a way to avoid it - declare new class MyChangeListener extends ChangeListener(code like @Sam), but I doubt it's more elegant one. Anyway patient is effectively final, and it's a good practice to put final explicitly.

public PerfilPaciente(int operation, Patient patient) {
tabPane.addChangeListener(new MyChangeListener(patient));
}

Upvotes: 0

Sam
Sam

Reputation: 1206

To avoid this, you can create an inner class that holds the information to process

public class MyOutterClass {
     ...

     public PerfilPaciente(int operation, Patient patient) {
         tabPane.addChangeListener(new MyChangeListener(patient));
     }

     ...

     //use an inner class that implements the interface
     //instead of an anonymous class declaration
     private class MyChangeListener implements ChangeListener {

         Patient patient;

         public MyChangeListener(Patient patient){
             this.patient= patient;
         }

         @Override
         public void stateChanged(ChangeEvent e) {
                switch (tabPane.getSelectedIndex()) {
                    case 1:
                        loadDates(patient);   // here is the problem
                        break;
                }
         }
     }
}

Upvotes: 1

Malcolm
Malcolm

Reputation: 41510

I can't fully understand the reasons why you don't want to make it final, but you could just make a copy of that variable:

final Patient patientFinal = patient;

And then

loadDates(patientFinal);

Upvotes: 0

assylias
assylias

Reputation: 328598

Up to Java 7 (inclusive) variables used inside an anonymous class need to be explictly final. In your case:

public PerfilPaciente(int operation, final Patient patient) {

With Java 8 this is not required any longer, the variable only needs to be effectively final (i.e. never reassigned in the enclosing method). So with Java 8 your code would compile.

Upvotes: 7

Related Questions