settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Define a class Person (OOP)

+7 votes

Define a class Person with fields for name and age.

Note: Add the following code to your main method:

public static void main(String[] args) throws Exception {
    Class person = Class.forName("Person");
    Field[] fields = person.getDeclaredFields();
    System.out.println(fields.length);
}

The output on the console should be 2. If you defined the class correctly, the test should pass.

Bonus*

Try to create a few objects of type Person:

Name

Age

Pesho

20

Gosho

18

Stamat

43

Use both the inline initialization and the default constructor.

asked in Java category by user eiorgert

1 Answer

+1 vote
 
Best answer

Here's the solution:

import java.lang.reflect.Field;

class Person {
    int age;
    String name;
}

public class U_17_Classes {
    public static void main(String[] args) throws ClassNotFoundException {
        Class person = Class.forName("Person");
        Field[] fields = person.getDeclaredFields();
        System.out.println(fields.length);
    }
}

 

answered by user hues
selected by user golearnweb
...