Code States BE 부트캠프 #10

John Jun·2023년 4월 24일
0

INDEX


1. Constructor

2. Inner Class


1. Constructor

A Constrcutor is the method that initialize the instance variables when the class is instantiated. Whent a class is instantiated with "new" keyword, a constructor initialize instance variables; there are several essential rules for constructor.

    1. The name of constructor must be same to the className.
    1. A constructor has NO RETURN TYPE and NO VOID keyword also.

      ClassName(parameter){...}
    1. A constructor also cane be overloaded with different parameters.
    1. If the developer doesn't make a Default Constructor(No parameters), Java compiler automatically makes one default constrctor when the instance of the class is made.
    1. Constructor Overloading makes it possible to use same Class in various ways with various variables without making new variable everytime making new instances.
  • this vs this()

this(): In a constructor, overloaded constructors can be called out with the method, this().

class Ex {
	public Ex() {
    System.out.println("the first constructor!")
    }
    
    public Ex(int x) {
    this(); 
    // this() methods that copies the default constructor in the overloaded second constructor.
    System.out.println("the second constructor!")
	    }
}
	
  • this() method must be used only in a constructor
  • this() method must be located the first line in a constructor.

this keyoword:

this keywords make it possible to use both the variables and parameters, which have same names, together with distingushing them in the constructors and methods: in the constructors and methods this. refers to the parameter in themselves.

  • This keyword refers to the instance(Object) itself: <this.parameterName = ...;>
  • It is generally used to distinguish instance field and local variables(or parameters), which have same name.

2. Inner Class

Inner Class is the class that is made inside of a class, which is only used when the outer calss and inner class are related, to reduce the complexity of codes.

profile
I'm a musician who wants to be a developer.

0개의 댓글