воскресенье, 12 апреля 2009 г.

Using inner classes

Hi all! In this post I want to tell you about inner classes. Very often, we create static inner classes that contains information about main class. For example:



public class Person {

private String name;

private String occupation;

public static class PersonInfo {

private String info;

public PersonInfo(String name, String occupation) {

info = “His name is ” + name + “ . He is a ” + occupation;

}

public String getInfo() {

return info;

}

}

public Person(String name){

this.name = name;

}

public void setOccupation(String occupation){

this.occupation = occupation;

}

public String getOccupation() {

return occupation;

}

public PersonInfo getInfo() {

return new PersonInfo(name, occupation);

}

}



This is a good example of using inner class. It demonstrates one of the main OOP conception – encapsulation. But it has one problem. If we put this object in some model, model don't know anything about Person and if Person object will be change, model won't know about this. And now I want to show powerful feature of inner class in java – this.outer:


public class Person {

  private String name;

  private String occupation;

  public class PersonInfo {

    public PersonInfo() {}

    public String getInfo() {

      return “His name is ” + this.Person.name +

                      “ . He is a ” + this.Person.occupation;

    }

}


public Person(String name){

  this.name = name;

}


public void setOccupation(String occupation){

  this.occupation = occupation;

}


public String getOccupation() {

  return occupation;

}


public PersonInfo getInfo() {

  return new PersonInfo();

}

}


Now, PersonInfo will return actually information about Person at anytime. And I shouldn't reload model that use it when Person object change. I can use feature this.superClass in anonymous class, too. Notice, that PersonInfo is not static. Actually, in first simple example PersonInfo is standalone class. In the second example, PersonInfo is in Person object.

Комментариев нет:

Most popular

Authors