[Java in NetBeans] Lesson 06. Custom classes

这个课程的参考视频和图片来自youtube

    主要学到的知识点有:

  • Constructors: A special method called when an object of the class is created
  • property pattern and encapsulation(封装): hide the implementation details from the user, so when the class is been inherited, only the methods, but not the members. 
  • this: simply refers to the current class. 
  • Also allow us to call other constructor in one constructor
public class Foo 
{
    private int _x;  // if class members, and not public, start with underscore.

    public Foo() 
    {
        this(1);
    }

    public Foo(int x)
    {
        _x = x;
    }
}
  • Overload: The method with different parameter but same method name. (for example, the constructors. Java will automatic search for the constructors that fits the parameters passed in)

             e.g. Foo foo = new Foo(8); will automatic search for the second constructor "public Foo(int x)".

  • Every class should have a constructor. But the body can be empty. 
  • Declare variables as private as possible. Can create getter and setter for the variables to control access to private variables.  based on the encapsulation(封装) concept. 
  • Initialize all private variables in constructor. (if not, make them final)
  • this disambiguates method parameters from private members, but will name the members with _(unless it is public). Below is an example without "_".
public class Foo 
{
    private int x;

    public Foo() 
    {
        this(1);
    }

    public int setX(int x)
    {
        this.x = x;
    }
}
  • Use get/set methods to control access to private variables. 

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10086486.html