My code is:
class Foo {
public int a=3;
public void addFive() {
a+=5;
System.out.print("f ");
}
}
class Bar extends Foo {
public int a=8;
public void addFive() {
this.a += 5;
System.out.print("b ");
}
}
public class TestClass {
public static void main(String[]args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
Output:
b 3
Please explain to me, why is the output for this question "b 3" and not "b 13" since the method has been overridden?
9) What is the output of the Java code snippet? Explanation: ASCII or UNICODE value of character 'A' is 65. A char value is converted to int before comparing it.
A code Snippet is a programming term that refers to a small portion of re-usable source code, machine code, or text. Snippets help programmers reduce the time it takes to type in repetitive information while coding. Code Snippets are a feature on most text editors, code editors, and IDEs.
A code snippet is a boilerplate code that can be used without changing it. This code helps such candidates who are not familiar with the online coding environment to focus more on the algorithm that is required to solve the question rather than understanding the STD INPUT and OUTPUT syntaxes.
What is a snippet in Java? As we discussed above JShell accepts statements, variables, methods, expressions, class definitions, and imports. These fragments (part or pieces) of Java code are called snippets. In general, the snippet is a section or piece of Java source code that save in XML format.
F
is a reference of type Foo
, and variables aren't polymorphic so f.a
refers to the variable from Foo
which is 3
How to verify it?
To test this you can remove a
variable from Foo
, it will give you compile time error
Note: Make member variable private
and use accessors to access them
Also See
You cannot override variables in Java, hence you actually have two a
variables - one in Foo
and one in Bar
. On the other hand addFive()
method is polymorphic, thus it modifies Bar.a
(Bar.addFive()
is called, despite static type of f
being Foo
).
But in the end you access f.a
and this reference is resolved during compilation using known type of f
, which is Foo
. And therefore Foo.a
was never touched.
BTW non-final variables in Java should never be public.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With