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


Download 1.52 Mb.
Pdf ko'rish
bet41/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   37   38   39   40   41   42   43   44   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

104.
105.
The class name i.e. Triangle is followed by the implements
keyword which is followed by the name of the interface that is
ShapeDrawer. Also, the Triangle class has code for the draw
method.
Is the following code snippet valid? Explain the reasons
either ways.
public abstract class MyAbstractClass {
public void doSomething() {
//doing something
}
public static void main(String args[]) {
MyAbstractClass obj = new MyAbstractClass();//Line
1
obj.doSomething(); //Line 2
}
}
Answer:
The above code is not valid and causes a compilation error at
Line 1. This code declares a class called MyAbstractClass
which is abstract. Line 1 instantiates the class and Line 2 invokes
the doSomething method. However, you cannot create an
object of an abstract class. Although this class does not contain
any abstract method, the class is still declared as abstract and so
it cannot be instantiated.
Can a class implement two interfaces? What will happen if
both the interfaces have a method with the same name?
Answer:


106.
Yes, a class can implement two interfaces. Even if both interfaces
have a method with the same name, this does not result in an
ambiguity as the implementation provided in the class is used.
The following code demonstrates this:
public interface MyInterface1 {
public void doSomething();
}
public interface MyInterface2 {
public void doSomething();
}
public class MyClass implements MyInterface1,
MyInterface2{
@Override
public void doSomething() {
// code here
}
}
MyClass obj = new MyClass();
obj.doSomething(); //Line 1
The above code specifies two interfaces MyInterface1,
MyInterface2. Both interfaces have a method called
doSomething. The code also specifies a class MyClass that
implements both the interfaces. It needs to provide an
implementation for the doSomething method. When Line 1 is
executed, the doSomething() method from MyClass is
executed.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   37   38   39   40   41   42   43   44   ...   171




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