forked from shiveeg1/JavaExamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerson.java
More file actions
80 lines (64 loc) · 1.83 KB
/
Person.java
File metadata and controls
80 lines (64 loc) · 1.83 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
package FifthExample;
//Here is an example of a simple class called 'Person'. It has two attributes and four methods.
//Note that the attributes are declared private so that they can only be accessed by the methods,
//not by anything outside the class.
//We are also showing the concept of chaining constructors.
// Finally, we're showing an example of a copy constructor where the argument passed to the constructor
// is another Person object of which we then do a copy of the attributes of the original.
class Person {
private String name;
private int age;
public static int numberOfPeople;
public Person() {
Person.numberOfPeople++;
System.out.println("number of people is " + Person.numberOfPeople);
System.out.println("Default constructor in chain");
}
// This is the second constructor called in the chain. Note that it calls
// the default constructor last
// and then sets the name.
public Person(String n) {
this();
this.name = n;
}
// This will be the first constructor called in the chain. It then calls the
// second constructor with
// only the name parameter and sets the age itself.
public Person(String n, int a) {
this("Barack Obama");
this.age = a;
}
// This is the copy constructor, notice that we expect another Person object
// and then we copy the
// attributes over.
public Person(Person p) {
this.name = p.name;
this.age = p.age;
}
public static String getEmployer() {
return ("Morgan Stanley");
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
final Person other = (Person) o;
if (this.name != other.name && this.age != other.age) {
return false;
}
return true;
}
int getAge() {
return this.age;
}
String getName() {
return this.name;
}
void setAge(int a) {
this.age = a;
}
void setName(String n) {
this.name = n;
}
}