Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code snippet output explanation required

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?

like image 586
Himanshu Aggarwal Avatar asked Aug 15 '12 17:08

Himanshu Aggarwal


People also ask

What is the output of this Java snippet?

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.

How do you explain a code snippet?

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.

What will be the output of code snippet?

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 code snippet in Java example?

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.


2 Answers

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

  • Why use getters and setters?
like image 198
jmj Avatar answered Sep 22 '22 02:09

jmj


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.

like image 29
Tomasz Nurkiewicz Avatar answered Sep 24 '22 02:09

Tomasz Nurkiewicz