Find the output of Java programs | final Keyword | Set 2: Enhance the knowledge of Java final Keyword concepts by solving and finding the output of some Java programs.
Question 1:
final class Sample {
static void sayHello() {
System.out.println("Hello World");
}
}
public class FinalEx extends Sample {
public static void main(String[] args) {
sayHello();
}
}
Question 2:
class Sample {
final static void sayHello() {
System.out.println("Hello World");
}
}
public class FinalEx extends Sample {
public static void main(String[] args) {
sayHello();
}
}
Question 3:
class Sample {
void sayHello() {
System.out.println("Hello World");
}
}
public class FinalEx {
public static void main(String[] args) {
final Sample S = new Sample();
S.sayHello();
}
}
Question 4:
class Sample {
final void fun() {
System.out.println("Sample.fun() called");
}
}
public class FinalEx extends Sample {
void fun() {
System.out.println("FinalEx.fun() called");
}
public static void main(String[] args) {
Sample S = new Sample();
S.fun();
}
}
Question 5:
class Sample {
final void fun() {
System.out.println("Sample.fun() called");
}
}
public class FinalEx {
void fun() {
System.out.println("FinalEx.fun() called");
}
public static void main(String[] args) {
Sample S = new Sample();
S.fun();
}
}
Answer Question 1:
Output:
Explanation:
The above program will generate syntax error because we cannot inherit a final class in Java.
Answer Question 2:
Output:
Explanation:
In the above program, we created two classes Sample and FinalEx. The Sample class contains a static final method sayHello(). Then we inherited the Sample class into FinalEx class then we called sayHello() method in the main() method of FinalEx class that will print "Hello World" on the console screen.
Answer Question 3:
Output:
Explanation:
In the above program, we created a class Sample that contains the method sayHello(). Then we created a FinalEx class that contains the main() method.
In the main() method we created an object of Sample class using the final keyword and then called the sayHello() method that will print "Hello World" on the console screen.
Answer Question 4:
Output:
Explanation:
The above program will generate syntax error because here we override method fun() of Sample class in FinalEx class. But we cannot override the final method in java.
Answer Question 5:
Output:
Explanation:
In the above program, we created two classes Sample and FinalEx. The Sample class contains a final method fun() and FinalEx class contains two methods fun() and main().
In the main() method we created the object S of Sample class then called fun() method of Sample class that will print "Sample.fun() called" on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer