多态性java错误

多态性java错误,java,polymorphism,Java,Polymorphism,这是模型类: 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 showEffec

这是模型类:

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);
 }
}
我试图创建一个与之非常相似的类,但它不起作用。我该换什么?我已经创建了所有这些类

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);
 }
}

当我试图编译它时,它会说:表达式的非法开始

在另一个方法中有一个方法,这在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);
      }
   }
} 
代码缩进不精确,这使您无法看到错误。相反,如果您努力使代码缩进良好,那么问题会立即变得显而易见,这就是为什么学习和使用适当的缩进非常重要的原因之一。这对于创建好的代码至关重要

解决方案:分开你的方法

其他方面的建议,你会想学习和使用。变量名都应该以小写字母开头,而类名应该以大写字母开头。遵循这些建议以及良好的代码格式化实践将允许我们这样的其他人!更好地理解你的代码,更重要的是,这将让你未来的自己更好地理解你在6个月前编写代码时的想法

另外,请注意错误消息的位置,因为它可能发生在有问题的嵌套方法的正上方。将来,如果您仔细查看编译器错误和JVM异常的位置,您通常会发现有问题的代码并能够修复它

您正在尝试使用一种常用方法,它的参数是 接受各种类的实例,在本例中是一件好事 do是为所有要实现的类提供一个接口。您也可以使用泛型

现在为其他类实现它:

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);
 }

 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);