What is the result of attempting to compile and run the following code?
class A {
public void method() {
System.out.println("A"); ,
}
}
class B extends A {
public void method() {
System.out.println("B");
}
}
public class Test {
public static void main(String[] args) {
A obj = new B();
obj.method();
}
}
The code demonstrates method overriding. The method() in class B overrides the method() in class A. At runtime, the method that is invoked is determined by the actual type of the object (B), so the output is "B".
Which access modifier allows access to a class member only within the same package and subclasses?
The protected access modifier allows access to class members within the same package and by subclasses, even if they are in different packages. private restricts access to the same class, public allows access from any class, and the default (package-private) modifier allows access only within the same package.
How can you create a class that cannot be subclassed?
In Java, a class declared with the final keyword cannot be subclassed. This ensures that no other class can extend it. The abstract keyword is used to declare a class that cannot be instantiated directly but can be subclassed, while static is used for class-level fields and methods, and private restricts access to members within the same class.
What is method overloading in Java?
Method overloading involves defining multiple methods with the same name but different parameter lists (different type or number of parameters) within the same class. It is a way to increase the flexibility of method use in Java.
What is the purpose of the "super" keyword in Java?
The super keyword is used to call the constructor of the superclass and access superclass methods and variables. It is not used to access private members (which are not accessible by subclasses), prevent method overriding, or create new instances of the superclass.