Java constructor transparent understanding article

  • 2021-11-10 09:47:20
  • OfStack

Directory 1. What are constructors 2. Features of constructors 3. Example 4. Default constructors 5. Overloading constructors 6. Use of constructors

1. What is a constructor

Java constructor, also called constructor, is a special function in JAVA. Same as function name, no return value.

Function: 1 is used to initialize member attributes and member methods, that is, after the new object is generated, the attributes and methods of the object are called.

In real life, when many things appear, they are born with certain attributes and behaviors. For example, when a person is born, he has age, height and weight, and he will cry; When a car is produced, it has color, appearance and can run.

Thus, we can define these natural properties and behaviors in the constructor. When new instantiates the object, it also has these properties and methods, so we don't need to redefine them, thus speeding up the programming efficiency.

The constructor is that Object 1 is created and run, initializes the object, including properties, and executes the statements in the method.

While 1 general function is executed only when the object is called, and the function is added to the object in the way of ". method name".

1 object is created, and the constructor only runs once.

And 1-like functions can be called multiple times by this object.

2. Features of constructors

1. The function name is the same as the class name

2. There is no need to define the return value type. (Unlike void type return values, void does not have a specific return value type; The constructor does not even have a type.)

3. You cannot write return statements. (There is no return value type, so return statement is not required.)

Note: 1 General functions cannot call constructors, and only constructors can call constructors.

3. Examples

1. Only one method is defined in the parameterless constructor class. The constructor is always called with new operation 1.

new object, the corresponding constructor is called to execute this method. You don't have to write ". Method name".


package javastudy;
 
public class ConfunDemo {
    public static void main(String[] args) {
        // Output Hello World . new Object 1 Is set, the corresponding constructor is called Confun() And execute the println Statement. 
        Confun c1=new Confun();            
        
    }
}
class Confun{        
    Confun(){        
        // Define the constructor, output Hello World
        System.out.println("Hellow World");
    }
}

Output:

Hellow World

2. Parametric constructor. When new object, it passes the argument value to private variable, which is equivalent to completing setter function.


package javastudy;
 
public class ConfunDemo3 {
    public static void main(String[] args){
        // When you instantiate an object, new Person() Call directly in Person Construct a function and turn the arguments, which is equivalent to setter Function 
        Person z = new Person("aerchi",18); 
        z.show();
    }
}
 
class Person{
    private String name;
    private int age;
    // Parameter constructor, which is implemented for private Function of transferring parameter values from member variables 
    public Person(String n,int m){ 
        name=n;
        age=m;        
    }
    //getter                                      
    // When the object is instantiated, the sett Function, you need to getter Gets the argument value. 
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
 
    // Get private Value, and print out 
    public void show(){
        System.out.println(name+"\n"+age);
    }
}

Output:

aerchi
18

In the above code, we can also put the output statement in the show () method directly in the constructor, and when the new object, we can directly output the value, as follows


package javastudy;
 
public class ConfunDemo3 {
    public static void main(String[] args){
        // When you instantiate an object, new Person() Call directly in Person Constructor and rolls the arguments, while executing the output statement 
        Person z=new Person("aerchi", 18);
    }
}
 
class Person{
    private String name;
    private int age;
    // Parameter constructor, which is implemented for private The function of transferring parameter values from member variables and directly outputting values at the same time 
    public Person(String n,int m){  
        name = n;
        age = m;
        System.out.println(name+"\n"+age);
    }
}

Output:

aerchi
18

Or


class ConFun
{
    public static void main(String[] args){
        Person a=new Person(18,"aerchi");
        System.out.println(a.getAge() +", " + a.getName());
    }
}
 
class Person
{
    private int age;
    private String name;
    public Person(int x,String y){
        age=x;
        name=y;
    }
    public int getAge(){
        return age;
    }
    public String getName(){        
        return name;
    }
}

3. After an object is created, the constructor only runs once.

If you want to assign a new value to the value of an object, you will use the set and get methods, which are used as 1-like functions in this case

As follows:


package javastudy;
 
public class ConfunDemo4 {
    public static void main(String[] args) {
            PersonDemo s=new PersonDemo(" Zhang 3",18);  //new Object, the corresponding constructor is called and a value is passed. At the same time, you can't new Same as 1 Object multiple times, otherwise an error will be reported. 
            s.setName(" Li 4");                       // After the object is created, when you want to change the value, you should use the set/get Method to reset the new value 
            s.setName(" Wang 2 Asako ");    // And can call the object multiple times. 
            s.print();
    }
}
class PersonDemo{
    private String name;
    private int age;
    PersonDemo(String n,int m){       // Creates a parameterized constructor for giving two private Variable name , age Assign a value and output a value at the same time 
        name=n;
        age=m;
        System.out.println(" Name: "+name+"\n"+" Age: "+age);
    }
    public void setName(String x){     //set Method, used to give it again name Assignment 
        name=x;        
    }
    public String getName(){          //get Method to get the name Assignment of 
        return name;
    }
    public void print(){
        System.out.println(name);
    }
}

Output:

Name: Zhang 3
Age: 18
Wang 2 pockmarked

4. Default constructor

When there is no constructor defined in a class, the system will add a default constructor with null parameters to the class to facilitate the initialization of the class. Only the empty constructor is hidden.

As follows, the default constructor Person () {} is hidden and not displayed.


class Person
{  
    //Person(){}
}

When the constructor is customized in this class, the default constructor is gone.

If you still want to construct the function, you need to add it manually in the class.

5. Overloading the constructor

Constructor is also a kind of function, which also has the characteristic of overloading function (Overloding).


class Person
{  
    private String name;
    private int age;
 
    Person()
    {
        System.out.println("A:name="+name+", age="+age);
    }
 
    Person(String n)
    {
        name = n;
        System.out.println("B:name="+name+", age="+age);
    }
 
    Person(String n,int a)
    {  
        name=n;
        age=a;
        System.out.println("C:name="+name+", age="+age);
    }
 
}
 
class PersonDemo2
{
    public static void main(String[] args)
    {
        Person p1=new Person();
        Person p2=new Person("aerchi");
        Person p3=new Person("aerchi",18);
    }
}

Output:

A:name=null, age=0
B:name=aerchi, age=0
C:name=aerchi, age=18


class Person
{  
    private String name;
    private int age;
 
    Person()
    {
        System.out.println("A:name="+name+", age="+age);
        cry();
    }
 
    Person(String n)
    {
        name = n;
        System.out.println("B:name="+name+", age="+age);
        cry();
    }
 
    Person(String n,int a)
    {  
        name=n;
        age=a;
        System.out.println("C:name="+name+", age="+age);
        cry(); 
    }
    void cry()
    {
        System.out.println("Haha ...............");
    }
 
}
 
class PersonDemo2
{
    public static void main(String[] args)
    {
        Person p1=new Person();
        Person p2=new Person("aerchi");
        Person p3=new Person("aerchi",18);
    }
}

Output:

A:name=null, age=0
Haha ...............
B:name=aerchi, age=0
Haha ...............
C:name=aerchi, age=18
Haha ...............

6. Use of constructors

1. All constructors of the subclass call the parameterless constructor of the parent class by default (the constructor will not be inherited, but only called by the subclass). The parameters of the parent class are private and cannot be accessed directly. You need to use the get method in the parent class to call the private variable value.


package javastudy;
 
public class ConfunDemo5 {
    public static void main(String[] args) {
        Pupil z=new Pupil();
        z.show();
    }
}
class Student{                // Parent class Student
    private String name;
    private int height;
    public Student()
    {
        this.name="";
        this.height=0;
    }
    public String getName(){
        return name;
    }
    public int getHeight(){
        return height;
    }
}
class Pupil extends Student{    // Subclass Pupil
    private int score;
    public Pupil(){                // Parametric constructor Pupil() Directly inherits the parameterless constructor in the parent class Student() But in the parent class name , height Yes private Adj. 
        score=0;
    }
    public void show(){
        System.out.print(" Name: "+getName()+"\n Height: "+getHeight()+"\n Scores: "+score);  // When outputting, directly use the get Method name. 
    }
}

2. Use super to call the constructor of the parent class

super must be written on the first line of the method


package javastudy;
 
public class ConfunDemo5 {
    public static void main(String[] args) {
        Pupil z=new Pupil(" Wang 2 Asako ",100,200);
        z.show();
        
        Pupil w=new Pupil();
        w.show();
    }
}
class Student{                // Parent class Student
    public String name;
    public int height;
    public Student()
    {
        this.name="";
        this.height=0;
    }
    public Student(String n,int m)
    {
        name=n;
        height=m;
    }
}
class Pupil extends Student{    // Subclass Pupil
    private int score;
    public Pupil(){                
        super(" Liu Dehua ",501);    // Use super Call parent class Student(String n,int m) Method while passing the actual value. super Must be written on the first line of the method. If it's written here super() Is called in the parent class Student() Method. 
        score=0;
    }
    public Pupil(String x,int y,int z){        //
        super(x,y);              // Use super Call parent class Student(String n,int m) Method , Among them super The parameter name in must be the same as the parameter name in the constructor 1 To. 
        score=z;
    }
    public void show(){
        System.out.println(" Name: "+name+"\n Height: "+height+"\n Scores: "+score);
    }
}

Output:

Name: Wang 2 Mazi
Height: 100
Score: 200
Name: Liu Dehua
Height: 501
Score: 0

Handyman


Related articles: