What to prefer if Java Interface and Abstract class have abstract methods only?

Technical interview question is that if an Interface and an abstract class in java both contains only abstract methods then what would you choose or prefer between java interface and abstract class and why?

This is true that abstract class can have a method implemented into it, but, the restriction is that it also contains only abstract class. For example,

/*----------------------------------------------
 * All methods in interface are by default
 * public and abstract. Just writing for
 * understanding purpose. However public and 
 * abstract declaration explicitly is also valid
 */

interface IShape{
	public abstract void f1();
	public abstract void f2();
}

//Abstractd class
abstract class ISqhape{
	public abstract void f1();
	public abstract void f2();
}

Answer:

Interface will be the preference over abstract class if an abstract class contains only abstract methods.

Reason is that, when any derive or client class try to implement any interface then he is having a option of extending another class. But, if the derived class using abstract class, then it will not be able to extend another class as java does not support multiple inheritance using classes but interfaces.

You can read multiple inheritance example in java using interfaces and description about support of multiple inheritance using classes.

Second reason, we can consider is that if we choose abstract class over interface as a software project design, then it may possible that after some time new software developer may implemented some methods in abstract class that will violet your design.

For example, he implements 2 classes and both contains a common method, say, read () method and inherits base class. As a good design, he may generalize 2 classes and can put read () method in abstract class. But, if he uses interface then he will not be able to do so.

For example. Below are two classes that contains common read () methods, so, they can be generalized and read() method can be moved to the abstract class.

class One extends IShape{
	
	void read(){}
	void f3() {}
	@Override
	public void f1() {		
	}
	@Override
	public void f2() {	
		
	}
}

class Two extends IShape{
	
	void read(){}
	void f4() {}
	@Override
	public void f1() {		
	}
	@Override
	public void f2() {	
		
	}
}

To generalize delete the read() method form both class and move to abstract class e.g.

abstract class IShape{
	public abstract void f1();
	public abstract void f2();
	void read(){}
}

Related Posts