The same code behaves differently
To create a base class (Super) and a derived class (Sub), each class has a field and a public method GetField, and is initialized to 1 using inline methods, and GetField returns the Fields field. C # and Java code and running results are as follows
C#
classSuper { Public intfield =0; Public intGetField () {returnfield; } } classSub:super { Public intfield =1; Public intGetField () {returnfield; } } classProgram {Private Static voidMain (string[] args) {Super sup=NewSub (); Console.WriteLine ("Sup.getfield () Result:"+Sup.getfield ()); Console.readkey (); } }
Java
classSuper { Public intfield = 0; Public intGetField () {returnfield; }}classSubextendsSuper { Public intfield = 1; Public intGetField () {returnfield; }} Public classpolymorphicdefects { Public Static voidMain (string[] args) {Super sup=NewSub (); System.out.println ("Sup.getfield () Result:" +Sup.getfield ()); }}
The results of the Java code Operation show Polymorphism, while the C # method does not show polymorphism. More specifically, the object sub in C # does not call its own method in the actual type sub, but instead calls the parent class's method.
may use the tube of Java children's shoes, suddenly use C # in a little bit unaccustomed, in fact, the C # team here added a concept, that is, reference access rights, a reference to represent his access rights, sub references can only be in the sub type of its own method access.
Of course, the C # method is not to support much, but to use virtual methods to express the polymorphism of the method, you can see the following example:
classSuper { Public intfield =0; Public Virtual intGetField () {returnfield; } } classSub:super { Public intfield =1; Public Override intGetField () {returnfield; } } classProgram {Private Static voidMain (string[] args) {Super sup=NewSub (); Console.WriteLine ("Sup.getfield () Result:"+Sup.getfield ()); Console.readkey (); } }
Next I would like to talk about my views on C # Introduction of reference access rights. The introduction of reference access to C # is more powerful than Java, but also more than Java a new feature, of course, there are two aspects, the introduction of the access to the reference also makes C # more complex and difficult.
I do not know the other children's shoes have no opinion, can be in the comment area more exchanges.
C # Reference access rights