Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 791
user1309724 Avatar asked Jul 19 '26 15:07

user1309724


2 Answers

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.

like image 91
Brian Roach Avatar answered Jul 21 '26 06:07

Brian Roach


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
    }
}
like image 23
Kartik Soneji Avatar answered Jul 21 '26 06:07

Kartik Soneji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!