Given the following, how would you create an object of class student named hank: IGNORE THE ONE | AFTER THE };| IT IS A TYPO. q20-22.JPG
Expert Answer
As per your question (and data provided) saying about object creation for classes, is performed differently in different programming languages.
For Java Programming Language.
If suppose class name is Student and object to be created is hank, then following line will create an object named hank.
Student hank = new Student();
In the above statement new is the keyword for creating an object.
If the student class has any parametrized constructor suppose the code below
class Student{
private String name; // member variable private String SID; // meber variable public Student() // default constructor { } public Student(String name, String SID) //parametrized constructor to set the value of member variables { this.name = name; this.SID = SID } // getter and setter methods below. } |
We can create the object by two ways for above class based on its constructor types.
1) First by calling its default constructor i.e., without passing any parameters to its constructor.
Suppose the object to be created is hank then
Student hank = new Student(); // calling default constructor.
2) Second, by calling its parametrized constructor.
Student hank = new Student(“Hank”, “1001”); // Calling its parametrized constructor.
For C/C++ Programming Language
There is no need to use the new operator while creating any object to a class in C/C++ .
Just, use the class name followed by the object name. Look at the following syntax.
Student hank; // for default constructor
Student hank(“Hank”, “1001”); // for parametrized constructor.