Posts

Showing posts with the label inheritance

Field overriding Java vs Scala

Inheritance is one of the foundations of object-oriented programming, it sounds straight forward on paper, but when it comes down the specifics, the rules are subtly different from language to language, and I will compare and demonstrate the subtlety with field overriding in Java and Scala . Java way Consider this example for field overriding in Java. public class Parent { protected static String name = "parent" ;      public String getName () {      return this .myName() ;      } } public class Child extends Parent { final static String name = "child" ; } public static void Main ( final String[] args) { final Parent parent = new Parent() ; final Child child = new Child() ; parent.getName() ; // "parent" child.getName() ; // "parent" } If you know Java, it's probably not hard to tell both "getName" results are "parent", and there is a legitimate reason for that, in Java, fields cannot be overr...