質問

I've been playing around inheritance and interface for a little bit and if I have a method with a parameter SomeClass c and I use c.interfaceMethod(); I get an error. How can I access this method c.interfaceMethod(); if I have a method with a parameter SomeClass c like I have here ?

public class SomeClass{
    public void someMethod(SomeClass c){

        c.interfaceMethod();      <-- how to access this method?
        //and other methods

        }

}

.

public class someOtherClass extends SomeClass implements someClassInterface{
    @Override
    public void interfaceMethod(){
        System.out.println("something");

    }
}

.

public interface someClassInterface{

    public void interfaceMethod();

}
役に立ちましたか?

解決

If you want interfaceMethod to be defined on SomeClass, you have to have SomeClass implement SomeClassInterface. If you only want to implement interfaceMethod in subclasses, you'll have to make SomeClass abstract.

So change your class declaration to:

public abstract class SomeClass implements SomeClassInterface {
    ...
} 

Also, by convention, all class and interface names should start with a capital letter.

他のヒント

You have to change like below to access:

public class SomeClass{
    public void someMethod(someOtherClass c){

        c.interfaceMethod();      --> to access this method
        //and other methods

        }

}

You can't access the method interfaceMethod of class someOtherClass in SomeClass.You need to create the object of someOtherClass to access it.

Can be updated as below :

public class SomeClass{
    public void someMethod(someOtherClass c){

        c.interfaceMethod();     
        //and other methods

        }

}

You need to implement someClassInterface in SomeClass as well

public class SomeClass implements someClassInterface {
public void someMethod(SomeClass c){

    c.interfaceMethod();      <-- now you can access this method
    //and other methods

    }

}

your class someClass is the super class of your class someOtherClass so the parent class "Super class" does not know any thing about someOtherClass"SubClass" and the method interfaceMethod() belongs to someOtherClass ,it's one of the inheritance fundamentals. read carefully http://docs.oracle.com/javase/tutorial/java/IandI/index.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top