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


Download 1.52 Mb.
Pdf ko'rish
bet34/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   30   31   32   33   34   35   36   37   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain the super keyword.
Answer:
The super keyword can be used in a sub–class to access the
base class instance fields or methods. It can also be used in a


088.
sub–class constructor to invoke the base class constructor.
Consider the following code snippet:
class Electronics {
protected double price;
public void displayPrice(){
//some code here
}
}
class Camera extends Electronics {
String cameraName;
public void setPrice(double price){
super.price = price; //Line 1
super.displayPrice(); Line 2
}
}
This code creates a class called Electronics which is the base
class and a class called Camera which is the sub class. Line 1
uses the super keyword to access the price field in the base class
Electronics. Line 2 uses the super keyword to access the
displayPrice method in the class Electronics
The code snippet below has an error. Identity it and state
the reason.
class Electronics {
public void displayPrice() {}
}
class Camera extends Electronics {
public void displayname() {}
}


089.
class TestElectronics {
public static void main(String argument[]) {
Electronics e = new Camera(); //Line 1
Camera c = new Electronics(); //Line 2
}
}
Answer:
In this code snippet, the code at Line 1 will compile fine since a
sub–class object can be assigned to a variable of a super–class
type. However, the code at Line 2 will cause a compilation error.
This is because a super class instance cannot be assigned to a
variable of the subclass type.
Write a code sample that demonstrates how inheritance
can help in code reuse
Answer:
Consider the following code:
class Electronics {
public void displayPrice() { //Line 1
System.out.println(“Price is ...”);
}
}
class Camera extends Electronics {
public void displayBatteryDuration() {
System.out.println(“Battery can withstand up to ...
hours”);
}
}
public class TestElectronics {


090.
public static void main(String argument[]) {
Camera c = new Camera();
c.displayPrice(); //Line 2
c.displayBatteryDuration();
}
}
In the above code, a class called Electronics is defined. It has
a sub–class called Camera. There is a displayPrice()
method (Line 1) defined in the Electronics class. Since
Camera is a sub–class, the displayPrice() method can be
invoked via a Camera instance as done at line 2. So, using
inheritance helps reuse code without having to write it again.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   30   31   32   33   34   35   36   37   ...   171




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