Call some methods from interface without override all the methods in JAVA

14,120

Solution 1

An interface is a contract. It says "My class implements all of these methods".

See: http://docs.oracle.com/javase/tutorial/java/concepts/interface.html

If you don't want that, don't use an Interface.

Solution 2

Java 8 allows default methods in an interface, that are used if the particular method is not overridden when the interface is implemented. For example:

interface MyInterface{
    //if a default method is not provided, you have to override it 
    public int Method1(); 
    public default int Method2(){
        return 2;
    }
}

public class MyClass{
    public static void main(String args[]){
        MyInterface in = new MyInterface(){
            public int Method1(){
                return 0;
            }
        };
        //uses the implemented method
        System.out.println(in.Method1()); //prints 0
        //uses the default method
        System.out.println(in.Method2()); // prints 2
    }
}

Solution 3

There is no other way than to implement all the methods in the interface, when you implement the interface. In the above class "samp" you are implementing "samp1" and "samp2" interface's, so you have to implement all the methods in samp1 and samp2 in samp class.

you said override methods from the interface. you don't override methods from interface, you just implement methods.

you can solve your problem by using abstract class.

abstract class AbstractSamp implement samp1,samp2{

 method1(){...}
 method4(){...}
}

and you can extend Abstractsamp in your samp class as below

class samp extends AbstractSamp{

// here you can extend method1() and method4() by inheritence and you can also    override   them as you want

}
Share:
14,120

Related videos on Youtube

user1309724
Author by

user1309724

Updated on June 05, 2022

Comments

  • user1309724
    user1309724 almost 2 years

    Friends, I have an issue in Java: I'd like to implement one structure but I'm facing some difficulty in doing it, can anyone help me.

    interface samp1{
        method1()
        method2()
        method3()
    }
    
    interface samp2{
        method4()
        method5()
    }
    class Samp implements samp1,samp2
    {
      // this class needs only method1 from interface samp1 and method 4 from interface samp2
      // I don't want to override all the methods from interface 
    }
    

    can anyone propose some solutions for this?

    Is there any design pattern available for this? If so, please provide links to reference.

    Thanks in advance.