Core java interview Questions You'll Most Likely Be Asked (Second Edition)


What is the difference between an abstract class and an


Download 1.52 Mb.
Pdf ko'rish
bet93/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   89   90   91   92   93   94   95   96   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

What is the difference between an abstract class and an
interface after Java 8?
Answer:




244.
The addition of Java 8 default interface methods has reduced the
distinction between abstract classes and interfaces. Prior to Java
8, interfaces could not have concrete methods. However, Java 8
has added default and static methods in interfaces. These are
methods that have a method body. This has further reduced the
distinction between abstract classes and interfaces. However,
there are there some differences between the two.These are as
follows:
Abstract classes can have instance fields. Interfaces on the
other hand cannot have instance fields. So basically, an
abstract class can have a state via an instance field, whereas
an interface cannot have state.
Abstract class can have a constructor and can be instantiated.
Interface on the other hand cannot have a constructor.
Write a code sample that demonstrates a default method.
Answer:
A default method is simply a method with a method body within
an interface. It has the default keyword. The following code
demonstrates this:
public interface MyInterface {
public void doSomething();
public default void doSomethingElse() {
System.out.println(“Doing something else....”);
}
}
This code has declared an interface called MyInterface. It has
an abstract method called doSomething() and a default
method called doSomethingElse(). The default method has
the default keyword specified. It has a method body.


245.



246.
What is the difference between a static and a default
interface method?
Answer:
Both static and default interface methods have a method body.
However, there are some differences between the two:
A static method has the static keyword specified, while a
default method has the default keyword specified.
Default interface methods can be overridden. Static methods
on the other hand cannot be overridden.
Default methods can be invoked via an object of the class that
implements the interface. Static interface methods on the
other hand cannot be invoked via the class or object of the
class that implements the interface. They need to be invoked
via the interface name.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   89   90   91   92   93   94   95   96   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling