-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2(Practical).java
More file actions
64 lines (59 loc) · 1.43 KB
/
Q2(Practical).java
File metadata and controls
64 lines (59 loc) · 1.43 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
Q2. Create a class TwoDim which contains private members as x and y
coordinates in package P1. Define the default constructor, a parameterized
constructor and override toString() method to display the co-ordinates. Now
reuse this class and in package P2 create another class ThreeDim, adding a new
dimension as z as its private member. Define the constructors for the subclass
and override toString() method in the subclass also. Write appropriate methods
to show dynamic method dispatch. The main() function should be in a package P.
/**** P1/TwoDim.java ****/
package P1;
public class TwoDim {
private int x;
private int y;
public TwoDim() {
this.x = 0;
this.y = 0;
}
public TwoDim(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Coordinate: x = " + x + " y = " + y;
}
}
/**** P2/ThreeDim.java ****/
package P2;
import P1.*;
public class ThreeDim extends TwoDim {
private int z;
public ThreeDim() {
super(0, 0);
this.z = 0;
}
public ThreeDim(int x, int y, int z) {
super(x, y);
this.z = z;
}
@Override
public String toString() {
return super.toString() + " z = " + z;
}
}
/**** P/Main.java ****/
package P;
import P1.*;
import P2.*;
public class Main {
public static void main(String[] args) {
TwoDim ref;
ref = new TwoDim(3, 6);
System.out.println(ref);
ref = new ThreeDim(2, 4, 7);
System.out.println(ref);
}
}
Output -
Coordinate: x = 3 y = 6
Coordinate: x = 2 y = 4 z = 7