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