Static and dynamic assignment assignment

Static assignment:

class A{
	
}
class B extends A{
	
}
class C extends A{
	
}

public class test {
	public void f(A a) {
		System.out.println("this is A");
	}
	public void f(B b) {
		System.out.println("this is B");
	}
	public void f(C c) {
		System.out.println("this is C");
	}
	
	public static void main(String[] args) {
		A b=new B();
		A c=new C();
		test t=new test();
		t.f(b); //this is A
		t.f(c); //this is A
	}
}

** Static assignment: ** all rely on static types to target the implementation of the method of dispatch version called static assignment.
Occurs at compile time, the typical application of method overloading (performed by the compiler, depending declared type of the variable).
Static assignment occurs at compile time, and therefore determine the static action assigned by the virtual machine is not actually performed.

Dynamic dispatch:

class A{
	public void f() {
		System.out.println("this is A");
	}
	
}
class B extends A{
	public void f() {
		System.out.println("this is B");
	}
}
class C extends A{
	public void f() {
		System.out.println("this is C");
	}
}

public class test {
	public static void main(String[] args) {
		A a=new A();
		A b=new B();
		A c=new C();
		a.f();//this is A
		b.f();//this is B
		c.f();//this is C
	}
}

Dynamic assignment:
at runtime is called dynamic assignment type determination method performed according to the actual version of the dispatch process. Typical applications are rewritten

class A{
	public void f() {
		System.out.println("this is A");
	}
	
}
class B extends A{
	public void f() {
		System.out.println("this is B");
	}
}
class C extends A{
	public void f() {
		System.out.println("this is C");
	}
}

public class test {
	public static void main(String[] args) {
		A a=new A();
		A b=new B();
		A c=new C();
		a.f();//this is A
		b.f();//this is B
		c.f();//this is C
	}
}

Dynamic method dispatch is to establish a method table area. If the child class does not rewrite the parent class, then the subclass vtable entry in the address of the parent class point to the same method, or subclass method table address is replaced as a method of pointing Subclasses override entry address .

Published 53 original articles · won praise 5 · Views 442

Guess you like

Origin blog.csdn.net/qq_45287265/article/details/104976358