user3079838
user3079838

Reputation: 83

Calling method from two different classes that have an implement

ok so I have to make a consoleprint interface class and two other classes that implement it

one class simply will let me print the text and the other u can see is string splitter. So far I have had problems with my tester

public interface ConsolePrint {

    public void printInfo(String infoToPrint);

}

public class SimplePrint implements ConsolePrint {

    public void printInfo (String infoToPrint) {
        printInfo("Heading this is not fancy");
    }
}

public class FancyPrint implements ConsolePrint {

    public void printInfo (String printInfo) {
        for (String splitter: printInfo.split("", 1)){
             System.out.println(splitter);
          }
    }
}

Heres the tester that I am getting problems from

import java.util.*;

public class ConsolePrintTest {

    public static void main(String[] args) {
    }

    SimplePrint mySp = new SimplePrint();
    FancyPrint myFp = new FancyPrint();

    myFp.printInfo(); <-----error appearing here

}

Any help would be great thanks

Upvotes: 1

Views: 252

Answers (3)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Move the statement inside some method (main in your case):

public static void main(String[] args) {


    SimplePrint mySp = new SimplePrint();
    FancyPrint myFp = new FancyPrint();

    myFp.printInfo("Test String"); //No error now
}

Upvotes: 1

Kevin Bayes
Kevin Bayes

Reputation: 846

You need to parse an argument into your printInfo method as there is no method that take no arguments called printInfo.

Try: myFP.printInfo("Hello world");

Additionally, you will get another error calling the SimplePrint implementation as it will never stop recursively calling the same function.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499780

You need to move your method call into your main method (or at least some method). Currently it's not in a method - only declarations (of fields, methods, nested types etc) can be at the top level of a class.

Additionally, you're not currently passing an argument to the printInfo method, but

So this would be fine:

public class ConsolePrintTest {
    public static void main(String[] args) {
        FancyPrint myFp = new FancyPrint();

        myFp.printInfo("some string");
    }
}

Note that:

  • I've removed the import in the class as it was irrelevant
  • I've removed the mySp declaration as that variable was never used
  • You're not currently using the fact that the classes implement the interface. You might want to consider:

    ConsolePrint printer = new FancyPrint();
    printer.printInfo("some string");
    

As noted in comments, your SimplePrint implementation recurses unconditionally too, so that's the nest problem to fix.

Upvotes: 3

Related Questions