为什么在重写的第一句有些时候要加这么一句调用父类方法的语句?有什么意义吗??

解决方案 »

  1.   

    原来的功能由super.paint()实现,自己要实现的功能写在下面.
      

  2.   

    给你看个例子class A {
        String s = null;
        public A() {
            System.out.println("create A");
        }    public void paint() { //注意这里
             System.out.println("set value to s");
            s = "test"; 
        }
    }public class B extends A {
        public B () {
            System.out.println("create B");
        }    public void paint() { //覆盖父类的方法
           //super.paint(); //注意这里,如果不调用super.paint,那么s还是null
           int n = s.length(); //所以这里就会出错了
            System.out.println("n=" + n);
        }
    }子类覆盖父类的方法时,父类的方法到底做了什么子类并不知道,而且父类的方法也许就做了很多重要的处理,如果子类不做这些处理就有可能带来不正确的结果,所以保险的做法还是调用一下父类的方法
      

  3.   

    How Lightweights Get Painted
    For a lightweight to exist, it needs a heavyweight somewhere up the containment hierarchy in order to have a place to paint. When this heavyweight ancestor is told to paint its window, it must translate that paint call to paint calls on all of its lightweight descendents. This is handled by java.awt.Container's paint() method , which calls paint() on any of its visible, lightweight children which intersect with the rectangle to be painted. So it's critical for all Container subclasses (lightweight or heavyweight) that override paint() to do the following:     public class MyContainer extends Container {
            public void paint(Graphics g) {
        // paint my contents first...
        // then, make sure lightweight children paint
        super.paint(g); 
            }
        } 
    If the call to super.paint() is missing, then the container's lightweight descendents won't show up (a very common problem when JDK 1.1 first introduced lightweights). 
      

  4.   

    “轻量级”部件是怎样被绘制的
       “轻量级”部件需要一个处在容器体系上的“重量级”部件提供进行绘画的场所。当这个“重量级”的“祖宗”被告知要绘制自身的窗体时,它必须把这个绘画的请求转化为对其所有子孙的绘画请求。这是由java.awt.Container的paint()方法处理的,该方法调用包容于其内的所有可见的、并且与绘画区相交的轻量级部件的paint()方法。因此对于所有覆盖了paint()方法的Container子类(“轻量级”或“重量级”)需要立刻做下面的事情:  
       
       public class MyContainer extends Container {
       public void paint(Graphics g) {
       // paint my contents first...
       // then, make sure lightweight children paint
       super.paint(g); 
       }
       }
       
       如果没有super.paint(),那么容器(container)的轻量级子孙类就不会显示出来(这是一个非常普遍的问题,自从JDK1.1初次引进“轻量级”部件之后)。