Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. What is a class constructor used for? 2. How do constructors differ from othe

ID: 3630274 • Letter: 1

Question

1. What is a class constructor used for?



2. How do constructors differ from other methods in a class?




3. What is the difference between private and public attributes and methods in a class?





Use the class below to answer questions 4 through 6.
public class Sample {

public int attrib1;
public double attrib2;
private String nameObject;
private final int PI = 3.14;

public Sample(int data1, String data2, double data3) {
attrib1 = data1;
nameObject = data2;
attrib2 = data3;
}
private int someMethod() {
//This method will return an integer value
return attrib1;
}

public double calcArea() {
//This method does not accept any arguments
return PI*attrib2*attrib2;
}
public double calcAreaWithRad(double rad) {
//This method accepts one integer argument
return PI*rad*rad;
}
}
4. Which attributes could be directly accessed from outside the class?


5. Which methods could only be called from inside the class?



6. Write a line of code to create an object instance of the Sample class using the constructor defined in the class, passing it three appropriate parameter values.

Explanation / Answer

1. It initializes the class variables to default values. It then calls the super class constructor (default constructor of super class only if no constructor is defined). It then initializes the class variables to the specified values. It then executes the body of the constructor. 2. The constructor do not have a return type. 3. for public, anyone can access to the attribute/methods. for private, only the class can that the contains the private attribute/methods can access it. 4. attrib1 and attrib2 5. someMethod() 6. Sample obj = new Sample(1,"data",1.1);