Can I ask you a question about Java programming?

Asked 2 years ago, Updated 2 years ago, 21 views

I re-coded it after looking at another example

If you look at the picture, I printed out the product instance p with println, and the toString was executed in the product class

I'm asking you this question because I don't know why the result was printed out.

java

2022-09-21 19:36

1 Answers

As you already know, when you print an object, the toString() of the object is executed. In the picture below, Product = new Product (3, "string") is initialized Product p2 = new Product() initialized

If you look at the Product class, there are two constructors, the first is the product (inti, string) that receives two arguments, and the second is the product() constructor without arguments. A name like function but with another argument is called function overloading.

p goes into the first constructor and has i = 3, st = "string" values p2 has i = 30, st = "dqwe".

So if you say System.out.println(p), you get 3 strings System.out.println(p2) gives 30 dqwe


2022-09-21 19:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.