0

Y is it im getting @2153person something like that as output plz make correction also tell me the reason. Code is below >>

public class MyClass { public static void main(String[ ] args) { Person j; j = new Person("John"); j.setAge(20); celebrateBirthday(j); System.out.println("Today is " +j+ "'s " +j.getAge()+ "st birthday"); } static void celebrateBirthday(Person p) { p.setAge(p.getAge() + 1); } } public class Person { private String name; private int age; Person (String n) { this.name = n; } public int getAge() { return age; } public void setAge(int a) { this.age = a; } }

29th Apr 2017, 2:00 PM
Mohammed Arshad
Mohammed Arshad  - avatar
3 Antworten
+ 7
j is treated as an object and as you haven't overidden toString method you get the reference to the object public class MyClass { public static void main(String[ ] args) { Person j; j = new Person("John"); j.setAge(20); celebrateBirthday(j); System.out.println("Today is " +j+ "'s " +j.getAge()+ "st birthday"); } static void celebrateBirthday(Person p) { p.setAge(p.getAge() + 1); } } public class Person { private String name; private int age; Person (String n) { this.name = n; } public int getAge() { return age; } public void setAge(int a) { this.age = a; } public String toString(){ return this.name; } } adding the public String toString() method will solve this
29th Apr 2017, 2:08 PM
Burey
Burey - avatar
+ 4
looks like you are printing an object... May be you wanted to print j.name?... May be you wanted to print j.getName()?... Either case you need to edit something. link your code playground program: it will be easier for others to provide help. The exact error you get might also be important.
29th Apr 2017, 2:08 PM
seamiki
seamiki - avatar
0
class Person should not be public as there is MyClass already declared as public.
29th Apr 2017, 2:07 PM
Vishal Prajapati