How to use the same add () method in two different classes

Is there any way you can use the same add () method between two different classes (add content to the array)? For example, my lake class has the following add () method:

public void add (Fish aCatchableThing) 
    {
        if (numThings < catchableThings.length)
        {
            catchableThings[numThings++] = aCatchableThing;
        }
    }

I'm trying to use the following code:

public class FishingTestProgram3 
{
    public static void main(String [] args) 
    {

        Lake   weirdLake = new Lake(21);
        weirdLake.add(new AuroraTrout(76,6.1f));
        weirdLake.add(new Tire());
        weirdLake.add(new Perch(32,0.4f));
        weirdLake.add(new Bass(20,0.9f));
        weirdLake.add(new Treasure());
        weirdLake.add(new Perch(30,0.4f));
        weirdLake.add(new AtlanticWhiteFish(140,7.4f));
        weirdLake.add(new RustyChain());
        weirdLake.add(new Bass(15,0.3f));
        weirdLake.add(new Tire());

This will be valid (using inheritance, i.e. endangeredfish extends fish, perch extends endangeredfish) for all added fish, but it does not work for objects (i.e. tire, rustychain, treasure) Tire, rustychain and treasure are classes that extend the sunkenobject class, which is actually empty:

public abstract class SunkenObject
{


}

I tried to create a second add method in the lake class, but failed I wonder if anyone has any idea how this works? There I can add everything (that is, fish and sunken objects) to the same array so that when

public void listAllThings() 
    {
        System.out.println("  " + this + " as follows:");
        for (int i=0; i<numThings; i++)
        {
            System.out.println("    " + catchableThings[i]);
        System.out.println();
        }

Print out all the contents of the array Thank you for your help

If anyone wants to know, this is the add () method I tried

public void add (SunkenObject sunkenObject) 
    {
        if (numThings < catchableThings.length)
        {
            catchableThings[numThings++] = sunkenObject;
        }
    }

Solution

The answer is almost in the question You want to add more than just fish instances to the lake What you want to add is something that can be captured So you need to define this type

Therefore, fish and sunkenobject should extend the public base class named catchablething, or implement the interface named catchablething

And the signature of the add () method should be

public void add(CatchableThing aCatchableThing)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>