How do we initialize the data members of a class when an object is initiated? Give an example.How do we initialize the data members of a class when an object is initiated? Give an example.?
In what programming language? You'd probably want to define a constructor for that class. In Java syntax:
public class Example
{
private int i;
private double d;
private String s;
//this is a constructor (notice, NO return type is specified):
public Example()
{
i = 0;
d = 0.0;
s = ';';;
}
//another constructor for the same class:
public Example(int i, double d, String s)
{
this.i = i;
this.d = d;
this.s = s;
}
}
Now I can create ';Example'; objects that have default values for its variables, or I can use the second constructor and specify initial values for the new object's member variable right there.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment