Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 10.4 WrClasses-WE2-P1
Subgoals for Writing a Class.
Pick a name for the class, is usually a noun
Differentiate class-level
static
vs. instance/object-level variables
Differentiate class-level
static
vs. instance/object behaviors/methods
Define instance variables (that you want to be interrelated)
Define class variables
static
as needed
Create constructor (behavior) that creates initial state of object
Overloaded constructor (with as many parameters)
Logic - initialize all variables
Repeat as needed, adding parameters
Create 1 accessor and 1 mutator behaviors per attribute
Return type same data type as attribute
Parameter is same data type as attribute
Logic validates input parameter and sets attribute value
Logic - convert needed attributes to a format that can be printed
Parameter - instance of the class
Logic - compare attributes for equity
Create additional methods as needed
Subsection 10.4.1
Consider the SongType class you began in an earlier exercise, as illustrated in the following UML diagram.
Figure 10.4.1.
Exercises Exercises
1.
Q9: Put the code in the right order to complete the default constructor.
public class SongType{
---
//attributes declared here
//...
//default constructor
public SongType(){
---
title = "";
artist = "";
length = 0;
---
}
}
2.
Q10: Put the code in the right order to complete the specific overloaded constructor.
public class SongType{
---
//attributes declared here
//...
//overloaded constructor
public SongType(String titleIn, String artistIn, double lengthIn){
---
title = titleIn;
artist = artistIn;
length = lengthIn;
---
}
}
3.
Q11: Which of the following is NOT true about constructors?
Constructors must be named the same name as the class
Incorrect
Default constructors have no parameters
Incorrect
Classes cannot have more than a single constructor
Correct
Constructors must be public
Incorrect
Constructors have no return type, not even void
Incorrect
4.
Q12: Two constructors are shown for the Point class below. Is this code valid?
public class Point {
private int x;
private int y;
public Point (int one, int two) {/*LOGIC*/}
public Point (int a, int b) {/*LOGIC*/}
}
Incorrect
Correct
Incorrect
You have attempted
of
activities on this page.