Inheritance and the “this” keyword

前端 未结 5 1726
有刺的猬
有刺的猬 2020-12-31 09:29

Suppose that we have next situation:

Parent class A:

class A{  
    public A(){}
    public doSomething(){  
        System.out.println(this.getCla         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-31 10:01

    Think of it in terms of runtime vs static types:

    Animal a = new Cat();
    

    The static type (in this case written on the left hand side) of variable a is Animal (you couldn't pass a into a method that required a Cat without a downcast) but the runtime type of the object pointed to by a is Cat.

    a.getClass() exposes the runtime type (if it helps think of it as the most specific subtype).

    Interestingly in Java overloaded methods are resolved at compile-time (without looking at the runtime type). So given then following two methods:

    foo(Cat c);
    foo(Animal animal)
    

    Calling foo(a) would call the latter. To 'fix' this the visitor pattern can be used to dispatch based on the runtime type (double dispatch).

提交回复
热议问题