[JAVA] [Head panic] Priority when variables / methods with the same name are used in inherited classes

A.java


public class A {
	String val = "A";
	void print() {
		System.out.println(val);
	}
}

B.java


public class B extends A {
	String val = "B";

    @Override
	void print() {
		System.out.println(val);
	}
}

Implement & execute the following using these classes

Main.java


public class Main {
	public static void main(String[] args) {
		A a = new A();
		 //Since B class inherits from A class, A can be used as the type of variable.
		A b = new B(); 
		
		//Since the type of b is A, val uses the value of the field defined in type A
		System.out.println("Show a val: " + a.val); // A
		System.out.println("Show val of b: " + b.val); // A
		
        System.out.print("print of a()Execute method: "); 
		a.print(); // A
		System.out.print("b print()Execute method: ");
		b.print();// B
     }
}

When displaying b.val, "A" is displayed Because we are using A as the type of variable b and the field of A is used.

On the other hand, "B" is displayed in b.print () This is because the print () method is overridden in the B class, and the B class method takes precedence when new B () is executed.

Note that the method is overridden, but the behavior changes because the variable is tied to the field.

Recommended Posts

[Head panic] Priority when variables / methods with the same name are used in inherited classes
Java learning_Behavior when there is a method with the same name as a field with the same name in two classes that have an inheritance relationship
[Head panic] Priority when variables / methods with the same name are used in inherited classes
Rails' Private methods hurt if you feel the same as Java!
If you have trouble with the character code problem in Myanmar (Burmese)
If you have trouble with JPA or Hibernate, don't google and look here first
What to do if you cannot execute with the command "Java package name / class name"
Ruby variables and methods
Ruby / rexml: Turn each with an element with the same name
Isn't there a name collision when enum has the same name in the switch statement?
When you get lost in the class name