手指的下面
时间长了,手指会痛
posts - 3,  comments - 2,  trackbacks - 0
子类继承父类
    1:子类方法优先检索并使用子类的方法
    2:子类与父类的属性都是存在,引用类型是父类时就使用父类属性,是子类就使用子类属性
    3
:调用父类方法(super.method()),父类方法中:
        调用方法,优先搜索子类中是否有该方法,然后是父类的;
        调用属性,则是使用父类的属性。
 1class Tree {
 2    int i = 3, j = 5;
 3
 4    public Tree() {
 5        this.show("Tree");
 6    }

 7
 8    protected void show(String s) {
 9        System.out.println(s);
10    }

11
12    public void t() {
13        this.show("Tree, t");
14        System.out.println(this.i);
15        System.out.println(this.j);
16    }

17}

18
19class Leaf extends Tree {
20    int i = 10;
21
22    public Leaf () {
23        this.show("Leaf");
24    }

25
26    public void show(String s) {
27        System.out.println(s + "\t\tLeaf");
28    }

29
30    public void t() {
31        show("Leaf, t");
32        System.out.println(this.i);
33        System.out.println(this.j);
34        System.out.println();
35        super.t();
36    }

37
38    public static void main(String args[]) {
39        Leaf l = new Leaf();
40        l.t();
41
42        System.out.println("------------------");
43        System.out.println(l.i);
44        Tree t = new Leaf();
45        l = (Leaf) t;
46        System.out.println(t.i);
47        System.out.println(l.i);
48    }

49}

50


打印结果:

 

Tree            Leaf
Leaf            Leaf
Leaf, t         Leaf
10
5

Tree, t         Leaf
3
5
------------------
10
Tree            Leaf
Leaf            Leaf
3
10

posted on 2008-08-18 22:13 xunSir.lee 阅读(192) 评论(2)  编辑  收藏 所属分类: Java

FeedBack:
# re: 类的继承
2008-08-19 23:47 | honeyjava
没有子类覆盖父类属性一说

/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2008-8-19
* Time: 23:34:32
* To change this template use File | Settings | File Templates.
*/

class Drived {
public int f = 2;


}

public class Foo extends Drived {
public int f = 1;


public static void main(String[] args) {

Drived foo = new Foo();
Foo foofoo = (Foo) foo;
System.out.println(foo.f);
System.out.println(foofoo.f);
}
}  回复  更多评论
  
# re: 类的继承
2008-08-20 22:30 | xunSir.lee
@honeyjava
谢谢,现在明白
继承时:
1.子类与父类的属性都是存在
引用类型是父类时就使用父类属性,是子类就使用子类属性
2.方法优先检索并使用子类
如果可以,能麻烦你解释一下,它们的内里机制吗?  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜