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
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.
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.
568 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
891 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
611 Uncaught (inpromise) Error on Electron: An object could not be cloned
568 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.