supertype instance = new subtype()声明instance为SUPERTYPE,限制了它哪些方法可以用,也就是只有SUPERTYPE里面生命的方法可用。
实例为SUBTYPE说明了所用的方法是如何执行的,也就是按照SUBTYPE里面OVERRIDE 后的方法执行
public class Example {
public void superExample1(){}
public void superExcample2(){}
}public class SubExample extends Excample{
public void superExample1(){
System.out.println("superexample is overrided in sub class");
}
public void subExample1(){
}
}Example ex = new SubExample()ex.superExample1() // 执行OVERRIDDED superExample1
ex.superExample2() // 执行父类里的superExample2
ex.subExample1() // complile-time error
实例为SUBTYPE说明了所用的方法是如何执行的,也就是按照SUBTYPE里面OVERRIDE 后的方法执行
public class Example {
public void superExample1(){}
public void superExcample2(){}
}public class SubExample extends Excample{
public void superExample1(){
System.out.println("superexample is overrided in sub class");
}
public void subExample1(){
}
}Example ex = new SubExample()ex.superExample1() // 执行OVERRIDDED superExample1
ex.superExample2() // 执行父类里的superExample2
ex.subExample1() // complile-time error
解决方案 »
- 请教如何让 JTable增加一行的时候新增的一行被选中,同时第一个cell处于全选中、可修改状态
- JDBC连接SQLServer2000的时候不能读取新建的数据库中的数据,但是可以读取SQL中内部的数据库,SQLServer已经打了SP3补丁,求帮忙
- 菜鸟问题 Sting和StingBuffer
- synchronized (dataSync) 是什么意思,synchronized是一个函数名吗
- java控制台
- 如何逐行显示table数据
- 怎样把字节流转换成字符数组或字符串?
- 对象生成的小问题
- sqlserver2000 的连接问题?急急急急急急急急急
- 高分求解安装jive的方法
- 用java方法可以读取批处理文件吗?
- Class。forName工厂模式遇到的问题求解
Java的动态绑定又称为运行时绑定。意思就是说,程序会在运行的时候自动选择调用哪儿个方法。一、动态绑定的过程: 例子:1 public class Son extends Father
2 Son son = new Son();
3 son.method();
1. 首先,编译器根据对象的声明类型和方法名,搜索相应类(Son)及其父类(Father)的“方法表”,找出所有访问属性为public的method方法。 可能存在多个方法名为method的方法,只是参数类型或数量不同。 2. 然后,根据方法的“签名”找出完全匹配的方法。 方法的名称和参数列表称为方法的签名。 在Java SE 5.0 以前的版本中,覆盖父类的方法时,要求返回类型必须是一样的。现在子类覆盖父类的方法时,允许其返回类型定义为原始类型的子类型。1 public Father getFather(){...} //父类中的方法
2 public Son getFather(){...} //子类覆盖父类中的getFather()方法
3. 如果是private、static、final 方法或者是构造器,则编译器明确地知道要调用哪儿个方法,这种调用方式成为“静态调用”。 4. 调用方法。 如果子类Son中定义了 method() 的方法,则直接调用子类中的相应方法;如果子类Son中没有定义相应的方法,则到其父类中寻找method()方法。二、Demo 1. 子类重写父类中的方法,调用子类中的方法复制代码
1 public class Father{
2 public void method(){
3 System.out.println("父类方法:"+this.getClass());
4 }
5 }
6 public class Son extends Father{
7 public void method(){
8 System.out.println("子类方法"+this.getClass());
9 }
10 public static void main(String[] args){
11 Father instance = new Son();
12 instance.method();
13 }
14 }
15 //结果:子类方法:class Son
复制代码
2. 子类没有重写父类中的方法,所以到父类中寻找相应的方法复制代码
public class Father{
public void method(){
System.out.println("父类方法:"+this.getClass());
}
}
public class Son extends Father{
public static void main(String[] args){
Father instance = new Son();
instance.method();
}
}
//结果:父类方法:class Son
复制代码
三、动态绑定只是针对对象的方法,对于属性无效。因为属性不能被重写。复制代码
1 public class Father{
2 public String name = "父亲属性";
3 }
4 public class Son extends Father{
5 public String name = "孩子属性";
6
7 public static void main(String[] args){
8 Father instance = new Son();
9 System.out.println(instance.name);
10 }
11 }
12 //结果:父亲属性