首页 > 解决方案 > 由于对象是子类,程序如何决定运行哪个方法

问题描述

所以我有以下代码:

import java.util.Scanner;

class Shape{
   double length, breadth;

   Shape(double l, double b) { //Constructor to initialize a Shape object  
      length = l;
      breadth = b;
   }

   Shape(double len) { //Constructor to initialize another Shape object  
      length = breadth = len;
   }

   double calculate(){ // To calculate the area of a shape object
      return length * breadth ;
   }
}

public class Test1 extends Shape {
   double height;

   Test1(double l, double h) {
      super(l);
      height = h;
   }

   Test1(double l, double b, double h) {
      super(l, b);
      height = h;
   }
   @Override
   double calculate(){
      return length*breadth*height;
   }   

   public static void main(String args[]) {
       Scanner sc = new Scanner(System.in);
       double l=sc.nextDouble();
       double b=sc.nextDouble();   
       double h=sc.nextDouble(); 
    
       Test1 myshape1 = new Test1(l,h);
       Test1 myshape2 = new Test1(l,b,h);
    
       double volume1;
       double volume2;
    
       volume1 = myshape1.calculate();
       volume2 = myshape2.calculate();
    
       System.out.println(volume1);
       System.out.println(volume2);
   }
}

而且我不明白它如何决定calculate()运行哪个方法,因为它们都是从子类对象调用的,但其中一个决定运行父类方法。

它与构造函数重载有关吗?如果是怎么办?

标签: javainheritanceoverridingconstructor-overloading

解决方案


构造函数重载与“运行哪个方法”无关。构造函数仅用于初始化实例,而“运行哪个方法”可能是与方法重载有关的问题,而您的问题并非如此。

在这两种情况下:

volume1 = myshape1.calculate();
volume2 = myshape2.calculate();

... ->类层次结构calculate()中的最低可用实现被调用 - 也就是说,在您的情况下。Test1java.lang.ObjectTest1::calculate

调用超类calculate(),而是您的类calculate()使用从超类继承的字段Shape,如下所示:

double calculate(){
      return length*breadth*height;
}

当您实例化类时,它是使用其超类的所有成员(甚至是私有的)创建的,这就是您使用超类字段的原因,就好像它们是在相关类中定义的一样。

旁注:private超类的成员在子类中不可直接访问。您需要适当的访问器/获取器来访问它们。


推荐阅读