Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question error while trying to compile an interface

    hello all
    i'm trying to learn about interfaces. my understanding is that an interface forces the class implementing it to call all the method variables defined in it. am i right about the basic idea?

    this is a little code i've written just to see if i got it right and i can't compile it for a few reason. i have two .java files: myInterface and myClass:

    PHP Code:
    // The interface
    public interface myInterface {
        public 
    void printWord (String word);

    PHP Code:
    //Class implementing it 
    class myClass implements myInterface {

        public static 
    void main (String[] args) {
        
    String word="Hello World";
        
    printWord(word);
        }

        public 
    void printWord(String word) {
        
    System.out.println(word);
        }

    The error i keep getting:
    PHP Code:
    myClass.java:5non-static method printWord(java.lang.Stringcannot be referenced from a static context
        printWord
    (word);
        ^
    1 error 
    so first - how do i make it right.
    second - can the interface, class implementing it and the method all be in the same file?

    thank you!

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Your implementation is correct, but your usage is wrong.
    printWord is not static. You must call it from an instance of myClass:
    PHP Code:
    public static void main(String[] argv)
    {
        
    String word "hello world";
        
    myClass mc = new myClass();
        
    mc.printWord(word);

    An interface is a contract. It guarantees that an Object of type myInterface will have a method called printWord implemented. Its up to the class how to do this, it could very well be nothing more than an exception toss. This is done to emulate multiple inheritance through polymorphism since Java does not natively allow extensions from multiple parents. Interfaces are at least 100x more useful than an extends anyway, so that really doesn't matter.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •