82.0k views
3 votes
Define a class Person that represents a person. People have a name, an age, and a phone number. Since people always have a name and an age, your class should have a constructor that has those as parameters.

2 Answers

3 votes

Answer:

The class and constructor in C++ is as follows:

class Person {

public:

string name; int age; int phone;

Person (string x, int y) {

name = x; age = y;

}

};

Step-by-step explanation:

This defines the class

class Person {

The specifies the access specifier

public:

This declares the attributes; name, age and phone number

string name; int age; int phone;

This defines the constructor for the name and age

Person (string x, int y) {

This gets the name and age into the constructor

name = x; age = y;

}

};

User Entea
by
3.8k points
1 vote

Answer:

public class Person {

String name;

int age;

String phoneNumber;

public Person(String name, int age, String phoneNumber){

this.name = name;

this.age = age;

this.phoneNumber = phoneNumber;

}

}

Step-by-step explanation:

The code above is written in Java.

The following should be noted;

(i) To define a class, we begin with the keywords:

public class

This is then followed by the name of the class. In this case, the name is Person. Therefore, we have.

public class Person

(ii) The content of the class definition is contained within the block specified by the curly bracket.

(iii) The class contains instance variables name, age and phoneNumber which are properties specified by the Person class.

The name and phoneNumber are of type String. The age is of type int. We therefore have;

String name;

int age;

String phoneNumber;

(iv) A constructor which initializes the instance variables is also added. The constructor takes in three parameters which are used to respectively initialize the instance variables name, age and phoneNumber.

We therefore have;

public Person(String name, int age, String phoneNumber){

this.name = name;

this.age = age;

this.phoneNumber = phoneNumber;

}

(v) Notice also that a constructor has the same name as the name of the class. In this case, the constructor's name is Person.

User Tianhao Zhou
by
3.4k points