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


Write a Java code sample that demonstrates method


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

Write a Java code sample that demonstrates method
overriding.
Answer:
Method overriding occurs when a sub–class method has the
same name and type signature as a method in a superclass.
Consider the following code:
public class Electronics {
public void charge() {
System.out.println(“All Electronics product has to
be charged”);
}
}
public class Camera extends Electronics {
public void charge() {
System.out.println(“The Camera has to be charged
periodically”);


091.
092.
}
}
In the above code, Camera is a subclass of Electronics. Both
classes have a method called charge() with the same type
signature. So, the charge() method in the Camera class is said
to override the charge() method in the Electronics class.
Explain the extends keyword with a code sample.
Answer:
The extends keyword can be used to specify that a class is a
sub–class of another class. It is specified in the sub–class
declaration. It should be followed by the name of the super class.
The following code demonstrates this:
public class Animal {
}
public class Dog extends Animal {
}
Here, Animal is a base class and Dog is a sub–class. The
extends keyword is used in the Dog class to specify that Dog is
a sub–class of animal.
What will be the output of the following code snippet?
public class Shape {
public Shape() {
System.out.println(“Shape Constructor”);
}
}
public class Circle extends Shape{


093.
public Circle() {
System.out.println(“Circle constructor”);
}
public static void main(String args[]) {
Circle circle = new Circle();
}
}
Answer:
The above code prints the following output:
Shape Constructor
Circle constructor
This is because a sub–class constructor automatically invokes a
base class constructor. Not only that, the call to the base class
constructor occurs before the code in the sub–class constructor
is executed. So, in this case, when the Circle constructor is
invoked, it first invokes the Shape constructor and then executes
the code in the Circle constructor.

Download 1.52 Mb.

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




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