简体   繁体   中英

Passing abstract class as parameter in java

I thought I did this before, maybe it was in C++. Here is the situation.

public abstract class SuperClass
{
   public methodname ( SuperClass superc )
   {
      // do stuff
   }
}

public class SubClass extends SuperClass
{
}

If I call this, I get an error

SubClass subc1 = new SubClass();
SubClass subc2 = new SubClass();

subc1.methodname ( subc2 );

It tells me that there is no method called "methodname (SubClass)". It does not want to use the SuperClass part of the SubClass and pass it in parameter to "methodname (SuperClass)". But if I remove the "abstract" keyword, there is no problem.

Does java allow passing abstract classes in parameter?

Your method is missing a return type, once I fix the error the code looks like:

public class Foo {
    public static void main(String[] args) {
        SubClass subc1 = new SubClass();
        SubClass subc2 = new SubClass();
        subc1.methodname ( subc2 );
    }
}

abstract class SuperClass
{
   public void methodname ( SuperClass superc )
   {
      System.out.println("do stuff");
   }
}

class SubClass extends SuperClass
{
}

with the superclass and subclass made non-public so I can cram everything into one file. I assume you had these classes in different files since both the superclass and subclass are public. When I compile and run it:

C:\Users\ndh>%JAVA_HOME%\bin\javac Foo.java

C:\Users\ndh>java Foo
do stuff

it works fine.

When I first compiled the original code I got this error:

C:\Users\ndh>%JAVA_HOME%\bin\javac Foo.java
Foo.java:12: error: invalid method declaration; return type required
   public methodname ( SuperClass superc )
          ^
1 error

All methods have to have a return type. Constructors have no return type but they have to be named the same as the class, so there shouldn't be ambiguity. javac correctly figures out what the problem is.

Maybe you're using an IDE that produces a less clear error message?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM