-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathConstructorCheat.java
More file actions
78 lines (62 loc) · 2.05 KB
/
ConstructorCheat.java
File metadata and controls
78 lines (62 loc) · 2.05 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
/*
# Constructor
JLS7 8.8
Cannot be `abstract`, `static`, `final`, `native`,
`strictfp`, or `synchronized`.
Can however be `private` to prevent object construction,
e.g. in static utility classes.
*/
public class ConstructorCheat {
public static void main(String[] args) {
/*
# Default constructor
Constructor automatically defined if you don't define any other constructor.
Sets all fields to their default values.
*/
{
class Class {
Class(int i) {}
}
// ERROR: we did define a constructor Class(int),
// so the default constructor was not defined.
//new Class();
// TODO: is an empty constructor equivalent to the default constructor?
}
/*
# Method with the same name as the constructor
Horrendous, but valid.
A constructor is only considered if there is no return value.
*/
{
class Class {
int i;
Class(int i) { this.i = i; }
int Class() { return this.i; }
}
assert new Class(1).Class() == 1;
}
/*
# Constructor inheritance
Does not exist. You have to duplicate code:
http://stackoverflow.com/questions/1644317/java-constructor-inheritance
Likely rationale: otherwise all classes would have an empty constructor
derived from `Object`, and it does not make much sense to many classes.
*/
{
class Base {
public int i;
Base(int i) { this.i = i; }
}
// ERROR: would generate only the default constructor,
// which calls super(), which does not exist.
//class Class extends Base {}
// OK.
class Class extends Base {
Class(int i) {
super(i);
}
}
assert new Class(1).i == 1;
}
}
}