The difference between this and the class name

advertisements

I've asked this question Adding objects to an array. And now it has brought up another question.

Is there a difference between this: For class Patient:

public Patient(String ptNo, String ptName, int procType) throws IOException
{
    Patient.patientNo =  ptNo;
    Patient.patientName = ptName;
    Patient.procedureType = procType;
}

and this:

public Patient(String ptNo, String ptName, int procType) throws IOException
{
    this.patientNo =  ptNo;
    this.patientName = ptName;
    this.procedureType = procType;
}

I thought they were the same thing?


edit I have created these in the Patient class.

private static String patientNo;
private static String procedureDate;
private static String patientName;


public Patient(String ptNo, String ptName, int procType) throws IOException
{
  Patient.patientNo =  ptNo;
  Patient.patientName = ptName;
  Patient.procedureType = procType;
}

This code will only work if all three variables are static like this

public class Patient
{
 static String patientNo;
 static int procedureType;
 static String patientName;

 public Patient(String ptNo, String ptName, int procType) throws IOException
 {
     Patient.patientNo =  ptNo;
     Patient.patientName = ptName;
     Patient.procedureType = procType;
 }
}

Whereas something like this

public Patient(String ptNo, String ptName, int procType) throws IOException
{
   this.patientNo =  ptNo;
   this.patientName = ptName;
   this.procedureType = procType;
}

will work for non static variables, "this" simply is used to avoid confusion denote the object whose constructor is being called. Example

Patient p = new Patient("A","B",1);

would be same as saying

   p.patientNo =  ptNo;
   p.patientName = ptName;
   p.procedureType = procType;

EDIT

"this" comes to rescue in a situation like this

public class Patient
{
  String patientNo;
  int procedureType;
  String patientName;

  public Patient(String patientNo, String patientName, int procedureType) throws IOException
  {
     this.patientNo =  patientNo;      // variables in LHS are class members, RHS are method parameters
     this.patientName = patientName;
     this.procedureType = procedureType;
  }
}