- 4
What are constructors?
9 Answers
+ 1
class Student {
private:
int age;
public:
Student(int a) {
setAge(a);
}
void setAge(int a) {
age = a;
}
Int getAge() {
Return age;
}
};
0
Constructor in java is a special type of method that is used to initialize the object.
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
via http://www.javatpoint.com/constructor
0
Basically, a constructor is a special function of a class, with the same name, that has a role in instantiating and initializing (or we can very well say "constructing") an object for that class. It is impossible to create objects without constructors, so every class has a default constructor, even if the programmer does not specify it.
for example:
class Person{
int age;
float height;
public Person(int a, int h){
age=a;
height=h;
}
}
when I am declaring a data of type person, i can use my custom created constructor to initialize the values of age and height properties of the person:
Person mike = new Person(24,1.78);
or I can use the default constructor:
Person mike = new Person();
This example of using constructors is specific for c#, but the principle of constructors is the same for all programming languages.
0
thanks
0
be careful with that method of constructing though, in java in particular (not sure on c#) if you declare a constructer with parameters, you must also declare a constructor with no parameters, the jvm won't do it for you in that case so Person mike= new Person(); will throw an error unless you make that constructor as well
0
@william, you are right. I forgot to mention that.
0
The Person component receives a "name" attribute using props.
Fill in the blanks to use that value as the initial value for the "name" in the state.
Answer:
class Person extends React.Component {
state = {
name: this.props.name
}
}
0
The Person component receives a "name" attribute using props.
Fill in the blanks to use that value as the initial value for the "name" in the state.
Answer:
class Person extends React.Component {
state = {
name: this.props.name
}
}
- 6
Fill in the blanks to declare the class Student, with int data member called age. Student class has a constructor with one argument that sets the value of the age data member.
please tell me answer i am not understanding this code
class Student {
private:
int age;
:
Student(int a) {
setAge(
);
}
void setAge(int a) {
age = a;
}
getAge() {
age;
}
};