JAVA学习笔记之七继承和多态

继承和多态

 

public class Point2D {

    private int x;//定义成私有的在 扩展的类中不能直接调用的

    private int y; //定义成私有的在 扩展的类中不能直接调用的 在这里初始值为0

 

    public Point2D() {

    }

 

    public Point2D(int x, int y) {

        this.x = x;

        this.y = y;

    }

 

    public void setX(int x) { this.x = x; }

    public void setY(int y) { this.y = y; }

 

    public int getX() { return x; }

    public int getY() { return y; }

}

public class Point3D extends Point2D { // 扩展Point2D 

    private int z;  // 新增私有数据

 

    public Point3D() {

        super();//调用父类中的没有参数的构造函数

    }

 

    // 定义建构方法

    Point3D(int x, int y, int z) {

        super(x, y); //同时指定呼叫父类构造函数

        this.z = z;

    }

 

    // 新增方法

    public void setZ(int z) { this.z = z; }

    public int getZ() { return z; }

}

public class ExtendDemo {

    public static void main(String[] args) {

        Point3D p1 = new Point3D(1, 3, 4);

        Point3D p2 = new Point3D(); //调用这个public Point3D()没有参数 只是初始值

 

        System.out.printf("p1: (%d, %d, %d) /n",

            p1.getX(), p1.getY(), p1.getZ());

        System.out.printf("p2: (%d, %d, %d) /n",

            p2.getX(), p2.getY(), p2.getZ());

    }

}

执行结果;

p1: (1, 3, 4)

p2: (0, 0, 0)

 

 

收保护的成员(Protected) 有限制的调用

(包括可以被子类调用)

public class Rectangle {

    //受保护的member可以被子类调用

    protected int x;

    protected int y;

    protected int width;

    protected int height;

 

    public Rectangle() {

    }

 

    public Rectangle(int x, int y, int width, int height) {

        this.x = x; 

        this.y = y;

        this.width = width;  

        this.height = height;

    }

 

    public void setX(int x) { this.x = x; }

    public void setY(int y) { this.y = y; }

    public void setWidth(int width) { this.width = width; }

    public void setHeight(int height) { this.height = height; }

 

    public int getX() { return x; }

    public int getY() { return y; }

    public int getWidth() { return width; }

    public int getHeight() { return height; }

    public int getArea() { return width*height; }

}

public class Cubic extends Rectangle {

    protected int z;

    protected int length;

 

    public Cubic() {

        super();

    }

 

    public Cubic(int x, int y, int z, int length, int width, int height) {

        super(x, y, width, height);

        this.z = z;

        this.length = length;

    }

 

    public void setZ(int z) { this.z = z; }

    public void setLength(int length) { this.length = length; }

 

    public int getZ() { return z; }

    public int getLength() { return length; }

 

    public int getVolumn() { // 可以直接使用父类中的widthheight成员

        return length*width*height;

    }

}

public class ExtendCubic {

    public static void main(String[] args) {

        Cubic p1 = new Cubic(1,3,4,5,7,9); //int x, int y, int z, int length, int width, int height

        Cubic p2 = new Cubic(); //调用这个public Cubic() 没有参数 只是初始值

        System.out.printf("p1: (%d,%d) /n",

            p1.getVolumn(), p1.getArea());

        System.out.printf("p2: (%d) /n",

            p2.getVolumn());

    }

}

 

 

 

 

 

 

重写的方法(override)方法

 

1. 重写 返回类型相同

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 SafeArray extends SimpleArray{

       public SafeArray(int i){

       super(i);

}

//扩展类重写方法但接口与simpleArray 接口相同

public void setElement(int i,int data){

if(i<array.length)

       super.setElement(i,data);

}

}

2. 重写 返回类型不同

public class Point2D{

       projected int x;

       projected int y;

public Point2D(int x,int y)

{

       this.x=x;

       this.y=y;

}

public Point2D getCopyofMe()

{

       return new Point2D(x,y);

}

}

public class Point3D extends Point2D{

       protected int z;

       public Point3D(int x,int y,int z){

       super(x,y);

       this.z=z;

//返回不同类型的返回值

public Point3D getCopyOfMe(){

       return new Point3D(x,y,z);

}

}

}

   

OBJECT 是所有类的父类

public class SimpleCollectionDemo {

    public static void main(String[] args) {

        SimpleCollection simpleCollection = new SimpleCollection();

 

        simpleCollection.add(new Foo1("一号 Foo1"));

        simpleCollection.add(new Foo2("一号 Foo2"));

 

        Foo 1 f 1 = (Foo1) simpleCollection.get(0);

        f1.showName();

 

        Foo 2 f 2 = (Foo2) simpleCollection.get(1);

        f2.showName();

    }

}

 

public class SimpleCollection {

    private Object[] objArr;

    private int index = 0;

 

    public SimpleCollection() {

        //  预设10个对象空间

        objArr = new Object[10];

    }

 

    public SimpleCollection(int capacity) {

        objArr = new Object[capacity];

    }

 

    public void add(Object o) {

        objArr[index] = o;

        index++;

    }

 

    public int getLength() {

        return index;

    }

 

    public Object get(int i) {

        return objArr[i];

    }

}

public class Foo1 {

    private String name;

 

    public Foo1(String name) {

        this.name = name;

    }

 

    public void showName() {

        System.out.println("foo1 嘿" + name);

    }

}

 

public class Foo2 {

    private String name;

 

    public Foo2(String name) {

        this.name = name;

    }

 

    public void showName() {

        System.out.println("foo2 嘿" + name);

    }

}

运行结果

foo1 嘿一号 Foo1

foo2 嘿一号 Foo2

object 中的一些方法

toString()equals() hashCode()方法

public class ToStringDemo {

    public static void main(String[] args) {

        StringBuilder builder = new StringBuilder();//StringBuilder一个连接两个字符串的类"+"类似

        for(int i = 0; i < 10; i++)

            builder.append(i);

 

        System.out.println(builder.toString());//toString对对象的String描述,他返回sting实例

    }

}

 

equals()比较对象的内存地址是否相同。

clone()如何复制对象本身的方法。

public class Point implements Cloneable {//定义Point类,这个类可以复制自己

    private int x;

    private int y;

 

    public Point() {}

    public Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

 

    public void setX(int x) { this.x = x; }

    public void setY(int y) { this.y = y; }

 

    public int getX() { return x; }

    public int getY() { return y; }   

//这个类可以复制自己

    public Object clone() throws CloneNotSupportedException {

        // 呼叫父类的clone()来进行复制

        return super.clone();

    }  

}

public class Table implements Cloneable {// 要操作Cloneable

    private Point center;

 

    public void setCenter(Point center) {//定义了PointTable类的数据成员之一

        this.center = center;

    }

    public Point getCenter() {

        return center;

    }

 

    public Object clone ()

                     throws CloneNotSupportedException {

        // 呼叫父类的clone()来复制

        Table table = (Table) super.clone();

 

        if(this.center != null) {

            // 复制Point类型的数据成员

            table.center = (Point) center.clone();

        }

       

        return table;

    }

}

public class CloneDemo {

    public static void main(String[] args)

                         throws CloneNotSupportedException {

        Table table = new Table();

        table.setCenter(new Point(2, 3));

        Point originalCenter = table.getCenter();

 

        Table clonedTable = (Table) table.clone();

        Point clonedCenter = clonedTable.getCenter();

 

        System.out.printf("原来的Table中心:(%d, %d)/n",

           originalCenter.getX(), originalCenter.getY());

        System.out.printf("复制的Table中心:(%d, %d)/n",

           clonedCenter.getX(), clonedCenter.getY());

 

        clonedCenter.setX(10);

        clonedCenter.setY(10);

 

        // 改变复制品的内容,对原来的对象不会有影响

        System.out.printf("原来的Table中心:(%d, %d)/n",

           originalCenter.getX(), originalCenter.getY());

        System.out.printf("复制的Table中心:(%d, %d)/n",

           clonedCenter.getX(), clonedCenter.getY());

    }

}

 

final 关键字

final声明变量,变量的值不能在变(相当于常量)

final定义方法时,则表示该方法成员再也无法被子类重写(override

如果是在类上加上final关键字的话,类终止扩展,这个类不能被其他类继承。

 

 

多态

 

抽象类

public class ConcreteCircle extends AbstractCircle {

    public ConcreteCircle() {}

 

    public ConcreteCircle(double radius) {

        this.radius = radius;

    }

 

    public void render() {

        System.out.printf("画一个半径 %f 的实心圆/n", getRadius());

    }

}

public abstract class AbstractCircle {

    protected double radius;

 

    public void setRedius(int radius) { this.radius = radius; }

    public double getRadius() { return radius; }

 

    public abstract void render();

}public class HollowCircle extends AbstractCircle {

    public HollowCircle() {}

 

    public HollowCircle(double radius) {

        this.radius = radius;

    }

 

    public void render() {

        System.out.printf("画一个dddddddddddddddd半径 %f 的空心圆/n", getRadius());

    }

}public class CircleDemo {

    public static void main(String[] args) {

        renderCircle(new ConcreteCircle(3.33));

        renderCircle(new HollowCircle(10.2));

    }

 

  //  public static void renderCircle(AbstractCircle circle) {

  //      circle.render();

  //  }

}

运行结果:

画一个半径 3.330000 的实心圆
画一个dddddddddddddddd半径 10.200000 的空心圆

 

抽象类应用

public abstract class AbstractGuessGame {

    private int number;

 

    public void setNumber(int number) {

        this.number = number;

    }

 

    public void start() {

        showMessage("欢迎");

 

        int guess = 0;

        do {

            guess = getUserInput();

            if(guess > number) {

                showMessage("输入的数字较大");

            }

            else if(guess < number) {

                showMessage("输入的数字较小");

            }

            else {

                showMessage("猜中了");

            }

        } while(guess != number);

    }

 

    protected abstract void showMessage(String message);

    protected abstract int getUserInput();

}

import java.util.Scanner;

 

public class TextModeGame extends AbstractGuessGame {

    private Scanner scanner;

 

    public TextModeGame() {

        scanner = new Scanner(System.in);

    }

 

    protected void showMessage(String message) {

        for(int i = 0; i < message.length()*2; i++) {

            System.out.print("*");

 

        }

        System.out.println("/n"+ message);

        for(int i = 0; i < message.length()*2; i++) {

            System.out.print("*");

        }

    }

 

    protected int getUserInput() {

        System.out.print("/n输入数字:");

        return scanner.nextInt();

    }

}

public class GuessGameDemo {

    public static void main(String[] args) {

        AbstractGuessGame guessGame =

                    new TextModeGame();

        guessGame.setNumber(50);

        guessGame.start();

    }

}

运行结果:****

欢迎

****

输入数字:20

**************

输入的数字较小

**************

输入数字:30

**************

输入的数字较小

**************

输入数字:40

**************

输入的数字较小

**************

输入数字:2

**************

输入的数字较小

**************

输入数字:80

**************

输入的数字较大

**************

输入数字:60

**************

输入的数字较大

**************

输入数字:50

******

猜中了

******

接口(interface)

接口与类不同的是 一个类可以实现多个接口

public interface IRequest {

     public void execute();

}

public class HelloRequest implements IRequest { //使用了接口

    private String name;

 

    public HelloRequest(String name) {

        this.name = name;

    }

 

    public void execute() {

        System.out.printf("哈喽%s%n", name);

    }

}

public class WelcomeRequest implements IRequest {

    private String place;

 

    public WelcomeRequest(String place) {

        this.place = place;

    }

 

    public void execute() {

        System.out.printf("欢迎来到%s%n", place);

    }

}

public class RequestDemo {

    public static void main(String[] args) {

        for(int i = 0; i < 10; i++) {

            int n = (int) (Math.random() * 10) % 2;// 随机产生

            switch (n) {

                case 0:

                    doRequest(new HelloRequest("MY Friend"));

                    break;

                case 1:

                    doRequest(new WelcomeRequest("my web blog”));

            }

        }

    }

 

    public static void doRequest(IRequest request) {

        request.execute();

    }

}

 

运行结果:

哈喽MY firend

哈喽MY firend

哈喽MY firend

哈喽MY firend

哈喽MY firend

欢迎来到my web site

哈喽MY firend

哈喽MY firend

哈喽MY firend

欢迎来到my web site

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值