You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Current »

Question

public class B extends A {
    MCParticle mcParticle;
 
    B ( MCParticle particle){
       this.mcParticle = particle;  
      }
    }

As I understand things, the "this." is redundant. There is no variable named mcParticle in A or in any of the classes that it extends or interfaces that it implements.

Answer

It is true that the this. is redundant, but consider this similar code:

    public class B extends A{
      MCParticle mcParticle;
 
      B ( MCParticle particle){
         particle = particle;
      }
     }

this code will compile, since it is perfectly legal to reassign a parameter in Java, but it will certainly not do what you want it to do. For this reason people normally write

    public class B extends A{
      MCParticle mcParticle;
 
      B ( MCParticle particle){
         this.particle = particle;
      }
     }

which will not compile (but would compile if the member variable was called particle).

  • No labels