Consider the following class header for a class named Book. Which of the following is a valid constructor for this class if the class has private instance variables title (String) and pages (int)?
AP (Advanced Placement) · AP Computer Science A
Abstraction, Program Design and Its Impact:练习题
5 道选择题即时批改,另有 1 道文字题附完整解题步骤,全部围绕「Abstraction, Program Design and Its Impact」。
Which of the following best describes the purpose of a constructor in a Java class?
A class Student has an instance variable gpa. The constructor is defined as follows:
public Student(double gpa) {
gpa = gpa;
}
What happens when new Student(3.5) is called, assuming the instance variable is also named gpa?
A class Square is being designed. It needs to store the length of a side. Which of the following is the most appropriate way to declare the instance variable for side length to ensure encapsulation?
Consider the following class definition:
public class Runner {
private double distance;
public Runner(double d) {
distance = d;
}
public void addDistance(double d) {
distance += d;
}
}
If we execute the following code:
Runner r1 = new Runner(5.0);
r1.addDistance(2.5);
What is the value of distance in the object r1?
Part a: A software developer needs to create a Student class. Define a constructor that initializes a student's name (String) and their current GPA (double).
Part b: Write a method isEligible that returns true if the GPA is greater than or equal to 2.0, and false otherwise.
Part c: Explain why the instance variables should be declared as private and how the constructor helps in maintaining encapsulation.
先自己写一遍答案,再对照解题步骤。
* thinka提供的内容由AI生成,可能并非总是准确或最新。请将其用作辅助资源,并与官方材料进行核实。
想多做几道同类题目?立即开始练习这个课题,边做边批改。
立即练习