被保护的( protected)成员 public class Rectangle //受保护的 member protected int xi protected int yi protected int width protected int height public class Cubicextends Rectangle i public int getvolumn() //可以直接使用父类别中的 width丶 height成员 return length* width*height
被保护的(protected)成员 public class Rectangle { //受保护的member protected int x; protected int y; protected int width; protected int height; … } public class CubicextendsRectangle { … public int getVolumn() { //可以直接使用父类别中的width、height成员 return length*width*height; } }
重新定义( Override)方法 如果父类别中的定义并不符合您的需求, 可以在扩充类别的同时重新定义 ·可以重新定义方法的实作内容、成员的访 问权限,或是成员的返回值型态
重新定义(Override)方法 • 如果父类别中的定义并不符合您的需求, 可以在扩充类别的同时重新定义 • 可以重新定义方法的实作内容、成员的访 问权限,或是成员的返回值型态
重新定义( Override)方法 public class simplearray i protected int[] array public SimpleArray (int i)t array= new int[i]氵 public void setTlement(int i, int data) t array [i data public class SafeArrayextends simpleArray i //重新定义setE1 ement() public void setElementint i, int data)( if(i< arraylength) super setTlement(i data)i
重新定义(Override)方法 public class SimpleArray { protected int[] array; public SimpleArray(int i) { array = new int[i]; } public void setElement(int i, int data) { array[i] = data; } .... } public class SafeArrayextends SimpleArray { … //重新定义setElement() public void setElement(int i, int data) { if(i < array.length) super.setElement(i, data); } .... }
重新定义( Override)方法 实际运作的对象是 Safe Array的实例,所以 被呼叫执行的会是 SafeArray中重新定义过 的 setTlement0方法 Simp leArray simpleArray new SafeArray ( simpleArray. setTlement()i
重新定义(Override)方法 SimpleArray simpleArray = new SafeArray(); simpleArray.setElement(); • 实际运作的对象是SafeArray的实例,所以 被呼叫执行的会是SafeArray中重新定义过 的setElement()方法
重新定义( Override)方法 在衍生类别中想要呼叫基类的建构方法 可以使用 super0方法 要在衍生类别中呼叫基类方法,则可以如 使用 super methodName 条件限制 父类别中的方法或建构方法不能是" private" 也就是不能是私用成员
重新定义(Override)方法 • 在衍生类别中想要呼叫基类的建构方法, 可以使用super()方法 • 要在衍生类别中呼叫基类方法,则可以如 使用super.methodName() • 条件限制 – 父类别中的方法或建构方法不能是"private", 也就是不能是私用成员