Why are singleton objects more object-oriented?

后端 未结 7 2119
心在旅途
心在旅途 2020-11-29 04:38

In Programming in Scala: A Comprehensive Step-by-Step Guide, the author said:

One way in which Scala is more object-oriented than Java is that cla

相关标签:
7条回答
  • 2020-11-29 05:16

    It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.

    In fact, given an object a of a class A with the static method m(), it's considered bad practice to call a.m(). Instead it's recommended to call A.m() (I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:

    class A {
        public static void m() {
            System.out.println("m from A");
        }
    }
    public class B extends A {
        public static void m() {
            System.out.println("m from B");
        }
        public static void main(String[] args) {
            A a = new B();
            a.m();
        }
    }
    

    What will a.m() print?

    In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.

    Adding the same example in Scala:

    class A
    object A { 
      def m() = println("m from A") 
    }
    class B extends A
    object B { 
      def m() = println("m from B")
      def main(args: Array[String]) {
        val a = new B
        A.m() // cannot call a.m()
      }
    }
    
    0 讨论(0)
提交回复
热议问题