Fives. C language structure alternative
How to use some of the structures in the C language in Java
Article 19: Use class instead of structure
For the structure in the C language, Java can be replaced by class, but you should not let the members variables can be publicly accessed, and the member variable should be private, then provide some read and write operations to manipulate these variables, want to be more than C or The structural type in C , such a class is more secure, reflects the encapsulation of OOP. Sample code
Public class point {
Private float x;
PRIVATE FLOAT Y;
Public float getX () {returnix x;}
Public float gety () {return y;}
Public void setx (int x) {this.x = x;}
Public void sety {this.y = y;
}
Article 20: Use class level instead of joint
For this point, I don't explain it, I am interested in seeing what is going on. The book gave a famous Shape example
Article 21: Use class instead of enumeration structure
Java cancels the type of enumeration in the C language (Note: JDK5.0 has added this feature, interested in finding information), here is how to simulate this structure before 5.0.
C Language: Typedef Enum {Circle, Rectangle, Square} Shape
Java language:
Public class shape {
PRIVATE FINAL STRING NAME;
Public Shape (String Name) {this.name = name;}
Public string toString () {return name;}
Public Static Final Shape Circle = New Shape ("Circle");
Public Static Final Shape Rectangle = New Shape ("Rectangle");
Public Static Final Shape Square = New Shape ("Square");
}
In the future, you can use Shape.Circle, Shape.Square to access the variables, you can see that Java's implementation model is more secure, and it has a type check. Very beautiful design!
Article 22: Use the class and interface instead of the function pointer
Java is not independent of the class or interface function, any method is included in a certain class and instance, so the function pointer inside C can use class and interface instead, obvious example, such as the Compareable interface, An array that needs to be sorted, in the call
When arrays.sort (), you can pass a comparator that implements the Compareable interface. This is equivalent to a function pointer.