forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThisKeywordExample.java
More file actions
70 lines (55 loc) · 1.51 KB
/
ThisKeywordExample.java
File metadata and controls
70 lines (55 loc) · 1.51 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
package com.examplehub.basics.oop;
public class ThisKeywordExample {
public static void main(String[] args) {
Point point = new Point(3, 4);
System.out.println("x = " + point.x + ", y = " + point.y); /* x = 3, y = 4 */
Rectangle rectangle = new Rectangle();
System.out.println(rectangle); /* Rectangle{x=0, y=0, width=1, height=1} */
rectangle = new Rectangle(3, 4);
System.out.println(rectangle); /* Rectangle{x=0, y=0, width=3, height=4} */
rectangle = new Rectangle(1, 1, 3, 4);
System.out.println(rectangle); /* Rectangle{x=1, y=1, width=3, height=4} */
Counter counter = new Counter();
System.out.println(counter.increment().increment().increment().getCount()); /* 3 */
}
}
class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Rectangle {
private final int x;
private final int y;
private final int width;
private final int height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
@Override
public String toString() {
return "Rectangle{" + "x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + '}';
}
}
class Counter {
private int count = 0;
public Counter increment() {
count++;
return this;
}
public int getCount() {
return count;
}
}