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.
Do'stlaringiz bilan baham: