-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathRec1A.java
More file actions
90 lines (72 loc) · 2.74 KB
/
Copy pathRec1A.java
File metadata and controls
90 lines (72 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Scanner;
// This class demonstrates multiple references to the same object, as well as
// static vs. non-static variables.
public class Rec1A {
// Every Rec1A object has a name
private String name;
// All Rec1A objects share a count
private static int count = 0;
/**
* Returns this Rec1A's name
*/
public String getName() { return name; }
/**
* Changes this Rec1A's name. Throws IllegalArgumentException if the
* argument is null or blank.
*/
public void setName(String name) {
if (name == null || name.length() == 0) {
// Throw exception if name is invalid
throw new IllegalArgumentException("Name cannot be null or blank.");
} else {
this.name = name;
}
}
/**
* Creates a Rec1A object with the given name. Throws
* IllegalArgumentException if the name is null or blank.
*/
public Rec1A(String name) {
if (name == null || name.length() == 0) {
// Throw exception if name is invalid
throw new IllegalArgumentException("Name cannot be null or blank.");
} else {
// Assign the argument value to the data member
this.name = name;
// Increment the count
Rec1A.count++;
}
}
/**
* Test the Rec1A class by making several instances.
*/
public static void main(String[] args) {
// Note that count is accessed via the Rec1A class, not one of its
// instances!
System.out.println("Number of Rec1A objects created at start: " +
Rec1A.count);
Rec1A matilda = new Rec1A("Matilda");
// Again, note this is not matilda.count
System.out.println("Number of Rec1A objects created incl. Matilda: " +
Rec1A.count);
Rec1A lakshmi = new Rec1A("Lakshmi");
Rec1A owen = new Rec1A("Owen");
System.out.println("Number of Rec1A objects created after two more: " +
Rec1A.count);
// Note here that custom is another reference to the same object as
// matilda!
Rec1A custom = matilda;
System.out.println("Number of Rec1A objects created incl. custom: " +
Rec1A.count);
System.out.println();
Scanner stdin = new Scanner(System.in);
System.out.print("Enter a new name: ");
String name = stdin.nextLine();
custom.setName(name);
System.out.println();
System.out.println("custom's name: " + custom.getName());
System.out.println("matilda's name: " + matilda.getName());
System.out.println("lakshmi's name: " + lakshmi.getName());
System.out.println("owen's name: " + owen.getName());
}
}