Discuss / Java / 接口没有实例化方法,却能引用子类实例

接口没有实例化方法,却能引用子类实例

Topic source

alienation

#1 Created at ... [Delete] [Delete and Lock User]

“在使用的时候,实例化的对象永远只能是某个具体的子类,但总是通过接口去引用它”

public class Main {

   public static void main(String[] args) {
      // TODO: 用接口给一个有工资收入和稿费收入的小伙伴算税:
      Income[] incomes = new Income[] {new SalaryIncome(7500), new RoyaltyIncome(12000) };
      double total = 0;
      for (Income income:incomes) {
         System.out.println(income.getClass());
         total += income.getTax();
      }
      // TODO:      System.out.println(total);
   }

}

接口虽然没有实例化方法,但是可以通过子类向上转型的方式声明子类实例

上面income迭代的结果是

class SalaryIncome

class RoyaltyIncome

Joker.fu_95

#2 Created at ... [Delete] [Delete and Lock User]

接口没有构造方法,无法实例化,只能通过引用指向具体实现类


  • 1

Reply