+ 1

Why this code output is 8?

public static class Person{ int age= 8; public Person(int age ){ System.out.print (this.age); } } public static main class(String []Args) Person p=new Person(2); }

18th Jul 2018, 5:05 PM
Caty Zurano
Caty Zurano - avatar
3 Answers
+ 3
When instantiating the object p like this "Person p=new Person(2);", you are calling the "Person constructor, which takes an int parameter, but you are printing "System.out.print (this.age);", where the "this.age" refers to the class variable with the value of 8 instead of the parameter. To print the desired "2" just remove the "this." and leave the "age" variable, which would be the parameter. Hope this explanation helped you Caty.
18th Jul 2018, 5:55 PM
Roberto Guisarre
Roberto Guisarre - avatar
+ 2
Gracias Roberto. A veces me confunde el término static.
18th Jul 2018, 10:50 PM
Caty Zurano
Caty Zurano - avatar
+ 1
public Person (){ int age; age=this.age; System.out.print (age); } ------ Person p= new Person (); Person p1= new Person (2); //82
19th Jul 2018, 1:37 AM
kiki