示例代码:
- class TwoDShapes{
- private double width;
- private double height;
- //width 和 height的访问器方法
- double getWidth(){
- return width;
- }
- double getHeight(){
- return height;
- }
- void setWidth(double w){
- width = w;
- }
- void setHeight(double h){
- height = h;
- }
- //父类构造方法
- TwoDShapes(double w,double h){
- width = w;
- height = h;
- }
- void showDim(){
- System.out.println("width and height:"+ width +"and"+ height);
- }
- }
- class Triangel extends TwoDShapes{ //通过extends关键字继承
- String style;
- Triangel(String sty,double w,double h){ //子类构造方法,初始化对象的变量和继承TwoDShapes的width,height
- style = sty;
- setWidth(w);
- setHeight(h);
- }
- //或者
- Triangel(String sty,double w,double h){ //子类构造方法,super()调用父类构造
- super(w,h);
style = sty; - }
- double area(){
- //return width * height /2; //引用TwoDShapes的成员,不能访问private修饰的成员
- return getWidth()*getHeight()/2; //private 成员,可以通过访问器方法访问。
- }
- void showStyle(){
- System.out.println("style:"+ style);
- }
- }
- class Shapes{
- public static void main(String args[]){
- Triangel t1 = new Triangel();
- Triangel t2 = new Triangel();
- t1.width = 4; //普通赋值width,height 是public修饰
- t1.height =4;
- t1.style ="filled";
- t2.setWidth(8.0); //通过访问器方法设置,width,height是private修饰
- t2.setHeight(12.0);
- t2.style ="outlined";
- System.out.println("t1:");
- t1.showDim();
- t1.showStyle();
- System.out.println("t1.area:"+ t1.area());
- System.out.println("t2:");
- t2.showDim();
- t2.showStyle();
- System.out.println("t2.area:"+ t2.area());
- Triangel t3 = new Triangel("filled",4.0,4.0); //通过子类方法构建对象
- System.out.println("t3:");
- t3.showDim();
- t3.showStyle();
- System.out.println("t3.area:"+ t3.area());
- }
- }
---------------------------------------------------------------------------------------
使用super调用父类成员:
- class A{
- int i;
- }
- class B extends A{
- int i;
- B(int a,int b){
- super.i = a; //调用父类i
- i = b;
- }
- void show(){
- System.out.println("super.i:"+ super.i);
- System.out.println("subclass.i:"+ i);
- }
- }
- class UseSuper{
- public static void main(String args[]){
- B ob = new B(1,2);
- ob.show();
- }
- }