代码之家  ›  专栏  ›  技术社区  ›  Student

有没有任何编程语言可以覆盖2个类以上的方法?

oop
  •  1
  • Student  · 技术社区  · 14 年前

    例如,如果您有A类、B类继承A类和C类继承B类,那么是否有任何编程语言可以让C类重写A类的方法,即使B类不重写它?

    class A {
      method() {}
    }
    
    class B extends A{
    }
    
    class C extends B {
      //override method from A
      method(){}
    }
    
    5 回复  |  直到 14 年前
        1
  •  3
  •   Péter Török    14 年前

    当然,在大多数(如果不是全部)的OO语言中都可以做到这一点,例如在爪哇和C++中。

        2
  •  1
  •   Jigar Joshi    14 年前

    是的,这是非常普通的情况,Java是这样做的。

        3
  •  0
  •   Flavio    14 年前

    这个Ruby代码完全按照您的要求执行:

    class A
      def hello
        puts "hello from class A"
      end
    end
    
    class B < A
    end
    
    class C < B
      def hello
        puts "hello from C"
      end
    end
    
    B.new.hello
    C.new.hello
    

    一旦执行,您将得到以下输出:

    hello from class A
    hello from C
    
        4
  •  0
  •   rerun    14 年前

    一对一

    public class A
    {
        virtual public int retval(int x)
        {
            return x; 
        }
    }
    public class B : A
    {
    
    }
    public class C : B
    {
        public override int retval(int x)
        {
            return 3; 
        }
    }
    
    class Program
    {
    
        static void Main(string[] args)
        {
            A a  = new C();
            Console.WriteLine(a.retval(2).ToString());
    
        }
    }
    
        5
  •  0
  •   supercat    14 年前

    我认为,如果所有模块都重新编译,那么大多数通用语言都可以轻松地实现这一点。如果将重写添加到中级类(在编译子方法时没有此类)中,则某些类(包括c和vb.net)中存在gotcha。在这种情况下,如果不重新编译子类,则对其父方法的调用可能会绕过中级类(因为在编译子类传递时,这些中级类没有重写)。