This is a question from a beginner who doesn't know the concept of Java creator

Asked 2 years ago, Updated 2 years ago, 64 views

package test1;

public class test1 {

public static void main(String[] args) {    
    Animals dog = new Dog(3);       
    System.out.println(dog.age);

} }

================================================

package test1;

public class Animals {

int age=1;

}

================================================

package test1;

public class Dog extends Animals {

int age=2;

public Dog() {
}   

public Dog(int page) {
    age = page;
}   

}

I'm asking you this question because I'm curious about the exact role of the constructor while studying the constructor.

In the code above, the execution result is 1, and I want to clearly understand the concept of what the Dog() constructor does when creating a dog instance and what the Animals class data type does.

java constructor

2022-09-20 17:21

2 Answers

Use the new operator to call the constructor of that class. Create an instance by calling the constructor. Therefore, the constructor is the first method called when you create an object. Therefore, you can set parameters in the constructor to pass the value Used to set the initialization of a property.


2022-09-20 17:21

It's been a long time since I've played Java, so I'm not sure, but to go back to my memory and answer it...

First of all, the Dog() constructor has no role in the above code

Because the constructor executed in the main function is Dog(int page)

The default constructor creates a constructor that receives nothing as an argument if there is nothing in the class constructor, but it does not behave the same as the code you wrote.

Instead, if you explicitly create it as above and define a specific action within it, it will perform that action whenever the default constructor is called.

For the Animals class, the parent class that the Dog class inherited.

Dog dog = new Dog(3); 

If you wrote the code in the same form as this, 3 would have been output in the output statement, but because this object was type-casted to the Animals object, 1 was output, which is the age value of the Animals class.

If you are curious about this, I recommend you to study more about Java inheritance and type conversion.


2022-09-20 17:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.