Java inheritance vs. C# inheritance

前端 未结 4 951
南旧
南旧 2021-01-01 22:08

Let\'s say Java has these hierarchical classes:

class A 
{
}
class B extends A
{
    public void m()
    {
        System.out.println(\"B\\n\");
    }
}
clas         


        
4条回答
  •  不思量自难忘°
    2021-01-01 22:46

    What's the logic behind the Java designer's decision to print C-C-C instead of B-C-C?

    Java makes methods virtual by default. In the past there was an understanding that this was good practice, and at the time of Java's birth was perhaps at the peak of that understanding.

    These days – while many do hold to it – there is also more resistance to it (particularly as virtual methods open up the class to unexpected sub-class implementation choices).

    (NB. there is no right or wrong here, each approach has its advantages and disadvantages.)

    How can I change Java code to print out B-C-C just like C# does?

    Declare them final.

    How can I change C# code to print out C-C-C?

    Declare them virtual or abstract in the class that defines them (B in the question), and override in child classes.

提交回复
热议问题