1. Java constructor can call another constructor, such as
Class a {
Public a () {this (0);
Public A (INT I) {...}
}
And C constructor cannot call another constructor, such as
Class a {
PUBLIC:
A () {a (0);} // Construct a temporary object
A (int i) {...}
}
This is a useful feature, but C is reduced by this feature because of the default parameters. If a few constructor have the same code, then the code can be placed in a private's init (...) for each constructor call.
2. Java's public and protected functions are virtual functions (Borrow C :) Override, and the private function is not a virtual function; the C private function can also be virtual.
Java:
Class a {
Public void g () {f ();
Private void f () {system.out.println ("in a's f");}
}
Public Class B Extends a {
Private void f () {system.out.println ("in b's f");}
Public static void main (string args []) {
B b = new b ();
B.G (); //print "in a's f"
C :
Class a {
PUBLIC:
Void g () {f ();
Private:
Virtual void f () {cout << "in a's f" << endl;}
}
Class B: Public a {
PUBLIC:
Void f () {cout << "in b's f" << endl;
}
Int main () {
B B;
B.G (); // Print "In B's F"
}
3. When the Java constructor calls the virtual function, the meaning of the virtual function is retained, that is, the function version of the subclass Override is called, while the C constructor calls the virtual function to call the subclass Override function version.
Java:
Class a {
Public a () {f ();
protected void f () {system.out.println ("in a's f");}
}
Class b extends a {
Protected void f () {system.out.println ("in b's f");}
Static void main (string args []) {
B b = new b (); // print "in b's f"
}
}
C :
Class a {
PUBLIC:
A () {f ();
protected:
Virtual void f () {cout << "in a's f" << endl;}
}
Class B: Public a {
protected:
Virtual void f () {cout << "in b's f" << endl;}
}
INT main () {b b; // print "in a's f"
}
At this point, C is better than Java, because when the subclass is called in the parent class, the subclass is not fully constructed, which may be wrong.
4. C Override is more than Java loose, the type of Override's function return value (pointer or reference) can be a subclass of the parent class corresponding function returns value type, such as:
Class c {
}
Class D: public c {
}
Class a {
PUBLIC:
Virtual c * f () {
COUT << "in a" << endl;
Return 0;
}
}
Class B: Public a {
PUBLIC:
D * f () {
COUT << "in b" << endl;
Return 0;
}
}
Int main () {
A * a = new b ();
A-> f (); // Print "in B"
}
In Java, the return value of the subclass method must be the same as the return value of the Override's parent class method, as the following code is compiled:
Class c {
}
Class D Extends C {
}
Class a {
Public C f () {
Return NULL;
}
}
Class b extends a {
Public D f () {
Return NULL;
}
}
Error message:
F () in b cannot override f () in a; attempting to use incompatible return
Found: D
Required: C