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


Explain what will be the output of the following code


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

Explain what will be the output of the following code
snippet:
public class Animal {
public static void saySomething() {
System.out.println(“I am an animal”);
}
}
public class Dog extends Animal {
public static void saySomething() {
System.out.println(“I am a dog”);


}
public static void main(String args[]) {
Animal a = new Animal(); //Line 1
a.saySomething(); //Line 2
Animal b = new Dog(); //Line 3
b.saySomething(); //Line 4
Dog d = new Dog(); //Line 5
d.saySomething(); //Line 6
}
}
Answer:
This code will print the following output:
I am an animal
I am an animal
I am a dog
Lines 1 and 2 create an Animal object and invoke the
saySomething method which prints “I am an Animal”. Line
3 declares an Animal variable b but assigns it an object of type
Dog. Line 4 invokes the saySomething method using the
variable b. Normally, when a superclass variable is assigned a
sub–class object and an overridden method is invoked, the
version from the sub–class gets executed. However, in this case
though both the Animal and Dog classes have the
saySomething method, it is a static method. Static methods
cannot be overridden. So, Line 4 invokes the saySomething
method from Animal class and prints I am an Animal. Lines
5 and 6 create a Dog object and invoke the saySomething
method which prints I am a Dog.


094. What is the output of the following code snippet?
public class Shape {
public Shape() {
System.out.println(“Shape Constructor”);
}
public void printShape() {
System.out.println(“I’m a shape!”);
}
}
public class Circle extends Shape{
public void printShape() {
System.out.println(“I’m a Circle!”);
}
}
public class Triangle extends Shape {
public void printShape() {
System.out.println(“I’m a Triangle!”);
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape shape = new Shape(); //Line 1
shape.printShape();
Shape circle = new Circle(); //Line 2
circle.printShape();
Shape triangle = new Triangle(); //Line 3
triangle.printShape();
}
}



Download 1.52 Mb.

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




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