学习java第29天

一.java中的继承

 

1.浅层克隆和深层克隆

浅层克隆:主要复制基本对象值

深层克隆:当类存在聚合关系时,必须考虑聚合对象的克隆

2.java的继承

使用关键字extends表示   class 子类 extends 父类{}

public class Animal {

    private String name;  

    private int id;

    public Animal(String myName, String myid) {

        //初始化属性值

    }

    public void eat() {  //吃东西方法的具体实现  }

    public void sleep() { //睡觉方法的具体实现  }

}

 

public class Penguin  extends  Animal{

}

3.super关键字

实现对父类的访问,用来引用当前对象的父类

class Animal {

  void eat() {

    System.out.println("animal : eat");

  }

class Dog extends Animal {

  void eat() {

    System.out.println("dog : eat");

  }

  void eatTest() {

    this.eat();                    // this 调用自己的方法

    super.eat();                 // super 调用父类方法

  }

}

 

public class Test {

  public static void main(String[] args) {

    Animal a = new Animal();

    a.eat();

    Dog d = new Dog();

    d.eatTest();

  }

}

 

4.类型检测——向上转型/向下转型

向上转型语法:父类 对象 = new 子类 ()

 

 class Animal

 

 {

 

    public void eat()

 

    {

 

       System.out.println("父类的 eating...");

 

    }

 

}

 

class Bird extends Animal

 

{   

    @Override 

    public void eat()

 

    {

 

       System.out.println("子类重写的父类的  eatting...");

 

    }  

 

    public void fly()

 

    {

 

       System.out.println("子类新方法  flying...");

 

    }

 

}

 

public class Sys

 

{

 

    public static void main(String[] args)

 

    {

 

       Animal b=new Bird(); //向上转型

 

       b.eat();   

 

       sleep(new Male())

 

       sleep(new Female());

 

    }

 

    public static void sleep(Human h) 

 

        {

 

        h.sleep();

 

        }

 

}

向下转型格式:父类 对象1 = new 子类();

                         子类 对象2 = (子类) 对象 1;

 class Fruit

 

  {

 

    public void myName()

 

    {

 

       System.out.println("我是父类  水果...");

 

    }

 

}

 

class Apple extends Fruit

 

{

 

    @Override

 

    public void myName()

 

    {

 

       System.out.println("我是子类  苹果...");

 

    }

 

    public void myMore()

 

    {

 

       System.out.println("我的苹果树");

    }

 

}

 

public class Sys{

 

    public static void main(String[] args) {

 

       Fruit a=new Apple(); 

       a.myName();

 

 

       Apple aa=(Apple)a;

 

       aa.myName();

 

       aa.myMore();

       Fruit f=new Fruit();

 

        Apple aaa=(Apple)f; 

 

       aaa.myName();

 

       aaa.myMore();

 

    }

 

5.明天学习内容:动态绑定,静态变量,静态方法,静态代码块

 

posted @ 2020-08-03 16:19  鯨落  阅读(63)  评论(0编辑  收藏  举报