本文章学习自https://www.cnblogs.com/xyz-star/p/10152676.html
静态绑定是在编译的时候就确定调用的这个方法是哪个类的方法。不可以被继承或者继承后不可以被覆盖的方法就是静态绑定,变量也是静态绑定。
静态绑定的方法有static,final,private方法。
可以被继承后覆盖的方法就是动态绑定,动态绑定的方法要根据方法表在调用方法的时候先进行搜索。
将方法定义为private,final,static方法有利于系统的优化.
例子:
public class Shape {
public String name = "shape";
public static String staticName="staticshap";
public void printType() {
System.out.println("this is shape");
}
public static void printName() {
System.out.println("shape");
}
}
public class Circle extends Shape{
public String name = "circle";
public static String staticName="staticcircle";
public void printType() {
System.out.println("this is circle");
}
public static void printName() {
System.out.println("circle");
}
}
public class Test {
public static void main(String[] args) {
Shape shape = new Circle();
System.out.println(shape.name);
System.out.println(shape.staticName);
shape.printType();
shape.printName();
Shape shape2 = new Shape();
System.out.println(shape2.name);
System.out.println(shape.staticName);
shape2.printType();
shape2.printName();
Circle circle = new Circle();
System.out.println(circle.name);
System.out.println(circle.staticName);
circle.printType();
circle.printName();
}
}
执行结果
shape
staticshap
this is circle
shape
shape
staticshap
this is shape
shape
circle
staticcircle
this is circle
circle
解析:
name、staticName和printName为静态绑定,在新建变量(如下过程)的时候就会和变量绑定。所以新建变量类型是什么类型,这些静态绑定的变量或者方法就会跟这个类型相应的变量或者方法相同。
Shape shape;
Shape shape2;
Circle circle;
printType是动态绑定,要在初始化的过程中才可以确定最终跟谁绑定。及new 后面的内容为其绑定的内容.
本文详细解释了静态绑定和动态绑定的概念,通过具体代码示例展示了如何在Java中实现这两种绑定方式。静态绑定通常涉及static、final和private方法,而动态绑定则允许方法在运行时根据对象的实际类型进行绑定。
409

被折叠的 条评论
为什么被折叠?



