Java语言与面向对象程序设计(第2版)课件第5章.ppt
文本预览下载声明
                        第 5 章   继承与多态;继   承;电话卡
域:剩余金额
方法:拨打电话
查询金额;继承的 优点、目的;派 生 子 类;域 的 继 承;域 的 隐 藏;abstract class A {
  double m_a;
  abstract double sub();
  double get()
  {    return m_a;  }	}
class B extends A {
  double m_a;
  double sub()
  {    m_a -=1;    return m_a;  }
  double super_sub()
  {    super.m_a -=1;    return super.m_a;  }	};public class Application1 {
  public static void main(String[] args) {
    B b = new B();
    b.m_a = 100;
    System.out.println(b.get());
    System.out.println(b.sub());
    System.out.println(b.super_sub());  }	}
输出为:	0
			99
			-1;;b.m_a = 100;	    b.get()    b.sub()    b.super_sub();《要点》:
1)被隐藏的父类域在子类对象中仍占有独立的内存空间;
2)子类可通过 super 关键字或继承自父类的方法访问或处理继承自父类的域。;方法的 继承 与 覆盖;abstract class A {
  double m_a;
  abstract double sub();
  double get()
  {    return m_a;  }	}
class B extends A {
  double m_a;
  double sub()
  {    m_a -=1;    return m_a;  }
  double super_sub()
  {    super.m_a -=1;    return super.m_a;  }	
  double get()
  {    return m_a;  }	};《例》域的隐藏、方法覆盖、方法重载
class Point {			// 父类 int x = 0, y = 0 ; void move(int dx, int dy) 
	{ x += dx ; y += dy ; } 	} 
class RealPoint extends Point { 	// 子类float x = 0.0f, y = 0.0f ;		// 域的隐藏void move(int dx, int dy) 		// 方法的覆盖
	{ 	System.out.println(subclasss move);
		move((float)dx, (float)dy); } 
	void move(float dx, float dy) 	// 方法的重载
	{ x += dx; y += dy; } 	} ;public class Application1 {
  public static void main(String[] args) {
    RealPoint rp = new RealPoint();
    System.out.println(x: + rp.x +  y: + rp.y);
    rp.move(1,1);
    System.out.println(x: + rp.x +  y: + rp.y);
  }	
}
输出:	x:0.0 y:0.0 
			subclasss move 
			x:1.0 y:1.0;this;super
对当前对象的父类对象的引用;
作用:1)在构造函数定义中用  super(参数列表) 调用父类的构造函数;
public  class apple extends fruits
{   public apple(int price)
     {    super(price);    }
}
	     2)用super . 域名 引用父类的域;
《例5-5》 testSuper.java(第100页)
问题:第六行:my200.balance = 50是访问的哪一个类的balance?
	第七行:my200.getBalance()是访问的父类还是子类的函数?访问的是父类还是子类的变量?;class SuperClass
{
	int x;
	...
}
class SubClass ex
                            显示全部