多态性 java 错误

Polymorphism java error

这是模型 class:

public class Test4
{
    public static void main(String []args)
 {
        Rectangle2 one = new Rectangle2(5, 20);
        Box2 two = new Box2(4, 10, 5);

      showEffectBoth(one);
      showEffectBoth(two);
  }

 public static void showEffectBoth(Rectangle2 r)
 {
     System.out.println(r);
 }
}

我正在尝试创建一个与它非常相似的 class,但它不起作用。我应该改变什么?我已经创建了所有这些 classes。

public class testNew
{
 public void showEffectBoth(Rectangle3 r)
 {
  System.out.println(r);
 }

public static void main (String []args)
{
Rectangle3 one = new Rectangle3(5,20);
Box3 two = new Box3(4,4,4);
Box3 three = new Box3(4,10,5);
Cube3 four = new Cube3(4,4,4);

showEffectBoth(one);
showEffectBoth(two);
showEffectBoth(three);
showEffectBoth(four);
 }
}

当我尝试编译它时,它说:illegal start of expression

您在另一个方法中得到了一个方法 -- 这是您在 Java 中无法做到的。

public class testNew {
   public static void main (String []args) {
      Rectangle3 one = new Rectangle3(5,20);
      Box3 two = new Box3(4,4,4);
      Box3 three = new Box3(4,10,5);
      Cube3 four = new Cube3(4,4,4);

      showEffectBoth(one);
      showEffectBoth(two);
      showEffectBoth(three);
      showEffectBoth(four);

      // you can't nest this method here
      public void showEffectBoth(Rectangle3 one) {
         System.out.println(one);
      }
   }
} 

您的代码缩进不精确,这使您无法看到错误。相反,如果您努力使代码缩进得当,问题就会立即变得显而易见,这就是为什么学习和使用正确的缩进如此重要的原因之一。这对创建好的代码至关重要。

解决方案:分开你的方法。

其他 "side" 推荐,你会想要学习和使用 Java naming conventions。变量名称应全部以小写字母开头,而 class 名称应以大写字母开头。遵循这些建议以及遵循良好的代码格式化实践将使其他人(例如我们!)更好地理解您的代码,更重要的是,将使您未来的自己更好地理解您 6 个月前编写代码时的想法代码。

另外,请注意错误消息的位置,因为它可能会出现在有问题的嵌套方法的正上方。以后如果仔细查看编译器错误(和JVM异常)的位置,你会经常找到有问题的代码并能够修复它。

you are trying to use one common method which it's parameter is accepting instances of various classes, in this case one good thing to do is having an interface for all the classes to implement. you can use generics also.

public interface CommonInterface
{
  public void doSomeThing();
}

现在为其他人实施它 类:

public class Box implements CommonInterface
{   
 @Override
 public void doSomeThing(){
  //do some thing;
 }

 //other fields or methods

 }
}
public class Rectangle implements CommonInterface
{   
 @Override
 public void doSomeThing(){
  //do some thing;
 }

 //other fields or methods

 }
}

现在您可以使用如下常用方法:

 public void showEffectBoth(CommonInterface r)
 {
     r.doSomeThing();
 }

你可以这样称呼它:

Rectangle one = new Rectangle(5, 20);
Box two = new Box(4, 10, 5);

showEffectBoth(one);
showEffectBoth(two);

注意:你的界面里面可以没有任何东西,在这种情况下你也可以有例如:

 public void showEffectBoth(CommonInterface r)
 {
     System.out.println(r);
 }

  Rectangle one = new Rectangle(5, 20);
  Box two = new Box(4, 10, 5);

  showEffectBoth(one);
  showEffectBoth(two);