java继承

Blues
Blues 2019年05月30日

复用类

java 继承

可以基于已经存在的类构造一个新的类。继承已经存在的类就可以复用这个类的方法和域。在此基础上,可以添加新的方法和域,从而扩充新类的功能。


  • 面向对象最重要的特点之一,就是可以实现对象的复用。
  • 通过“继承”一个现有的类,可以使用已经定义的类中的方法和变量。
  • 类的方法可以被继承,但是类的构造器用private修饰的属性及方法不能被继承。

1. 继承的基本语法

父类

public class Father{
  ...//属性
  ...(){//方法
    ...
  }
}

子类

public class Son extends Father{

}

2. 继承的概念

继承是面向对象最显著的一个特征。继承是从以有的类中派生出的新类,新类能吸收已有类的数据属性和方法,并且扩展新的能力。

基本语法如下:

class 子类 extends 父类{}

java 继承的基本实现

clss Animal{
  private int weight;
  private int age;


  public int getWeight() {
           return weight;
       }

       public void setWeight(int weight) {
           this.weight=weight;
       }

       public int getAge() {
           return age;
       }

       public void setAge(int age) {
           this.age=age;
       }
}
class Dog extends Animal{  //Dog类继承了Animal类

}

public class ExtendsDemo{
  public static void main(String[] args){
    Dog dog=new Dog();
    dog.setAge(5);
    dog.setWeight(10);
    dog.speak();
System.out.println("age:"+dog.getAge+",weight:"+dog.getWeight);


  }
}

运行结果:

age:5,weight10

通过代码可以发现,子类(Dog)并没有定义任何的操作,而在主类中所使用的全部操作都是由 Animal 类定义的,这证明:子类即使不扩充父类,也能维持父类的操作。

在子类扩充父类的功能:

clss Animal{
  private int weight;
  private int age;


  public int getWeight() {
           return weight;
       }

       public void setWeight(int weight) {
           this.weight=weight;
       }

       public int getAge() {
           return age;
       }

       public void setAge(int age) {
           this.age=age;
       }
}
class Dog extends Animal{  //Dog类继承了Animal类
   private String color;

   public void speak(){
     System.out.println("wangwnagwang!!");
   }

   public String setColor(String color){
     this.color=color;
   }
   public void getColor(){
     return color;
   }

}

public class ExtndsDemo{
  public static void main(String[] args){
    Dog dog=new Dog();
    dog.setAge(5);
    dog.setWeight(10);
    dog.setColor("yellow");
    dog.speak();
System.out.println("age:"+dog.getAge+",weight:"+dog.getWeight+",color:"+dog.getColor);


  }
}

运行结果:

wangwangwang!!
age:5,weight10,yellow

3. java 继承的限制

  • 限制一:java 只允许单继承
    即:
class A {}
class B extends A {}
class C extends B {}
  • 限制二:
    在一个子类继承的时候,实际上会继承父类之中的所有操作(属性、方法),但是需要注意的是,对于所有的非私有(no private)操作属于显式继承(可以直接利用对象操作),而所有的私有操作属于隐式继承(间接完成)。
  • 限制三:
    在继承关系之中,如果要实例化子类对象,会默认先调用父类构造,为父类之中的属性初始化,之后再调用子类构造,为子类之中的属性初始化,即:默认情况下,子类会找到父类之中的无参构造方法。

4. 动态绑定

  • 1. 动态方法的绑定

将一个方法同一个方法主体连接在一起就称为绑定 (Binding)。若在运行运行前执行绑定,就称为“早期绑定”。上面的例子中,在只有一个 Dog 句柄的情况下,编译器不知道具体调用哪个方法。Java 实现了一种方法调用机制,可在运行期间判断对象的类型,然后调用相应的方法,这种在运行期间进行,以对象的类型为基础的绑定称为动态绑定。除非一个方法被声明为 final,Java 中的所有方法都是动态绑定的。

用一张图表示上溯造型的继承关系

binding

用代码概括为:

Shape s = new Shape();

按照继承关系,将创建的 Circle 对象句柄赋给一个 Shape 是合法的,因为 Circle 属于 Shape 的一种。

当调用其中一个基础类方法时:

Shape s = new Shape();

此时,调用的是 Circle.draw(), 这是由于动态绑定的原因。

动态绑定代码示例:

class Person {
    void eat() {}
    void speak() {}
}
class Boy extends Person {
    void eat() {
        System.out.println("Boy.eat()");
    }
    void speak() {
        System.out.println("Boy.speak()");
    }
}
class Girl extends Person {
    void eat() {
        System.out.println("Girl.eat()");
    }
    void speak() {
        System.out.println("Girl.speak()");
    }
}
public class Persons {
    public static Person randPerson() {
        switch ((int)(Math.random() * 2)) {
        default:
        case 0:
            return new Boy();
        case 1:
            return new Girl();
        }
    }
    public static void main(String[] args) {
        Person[] p = new Person[4];
        for (int i = 0; i < p.length; i++) {
            p[i] = randPerson();    // 随机生成Boy或Girl
        }
        for (int i = 0; i < p.length; i++) {
            p[i].eat();
        }
    }
}

对所有从 Person 衍生出来的类,Person 建立了一个通用接口,所有衍生的类都有 eat 和 speak 两种行为。衍生类覆盖了这些定义,重新定义了这两种行为。在主类中,randPerson 随机选择 Person 对象的句柄。上溯造型是在 return 语句里发生的。return 语句取得一个 Boy 或 Girl 的句柄并将其作为 Person 类型返回,此时并不知道具体是什么类型,只知道是 Person 对象句柄。在 main 方法中调用 randPerson 方法为数组填入 Person 对象,但不知具体情况。当调用数组每个元素的 eat 方法时,动态绑定的作用就是执行对象的重新定义了的方法。

然而,动态绑定是有前提的,绑定的方法必须存在于基类中,否则无法编译通过。

class Person {
    void eat() {
        System.out.println("Person.eat()");
    }
}
class Boy extends Person {
    void eat() {
        System.out.println("Boy.eat()");
    }
    void speak() {
        System.out.println("Boy.speak()");
    }
}
public class Persons {
    public static void main(String[] args) {
        Person p = new Boy();
        p.eat();
        p.speak();  // The method speak() is undefined for the type Person
    }
}
如果子类中没有定义覆盖方法,则会调用父类中的方法:

复制代码
class Person {
    void eat() {
        System.out.println("Person.eat()");
    }
}
class Boy extends Person {
}
public class Persons {
    public static void main(String[] args) {
        Person p = new Boy();
        p.eat();
    }
}

【运行结果】:

Person.eat()

5. 静态方法的绑定

将上面的方法都加上 static 关键字,变成静态方法:

class Person {
    static void eat() {
        System.out.println("Person.eat()");
    }
    static void speak() {
        System.out.println("Person.speak()");
    }
}
class Boy extends Person {
    static void eat() {
        System.out.println("Boy.eat()");
    }
    static void speak() {
        System.out.println("Boy.speak()");
    }
}
class Girl extends Person {
    static void eat() {
        System.out.println("Girl.eat()");
    }
    static void speak() {
        System.out.println("Girl.speak()");
    }
}
public class Persons {
    public static Person randPerson() {
        switch ((int)(Math.random() * 2)) {
        default:
        case 0:
            return new Boy();
        case 1:
            return new Girl();
        }
    }
    public static void main(String[] args) {
        Person[] p = new Person[4];
        for (int i = 0; i < p.length; i++) {
            p[i] = randPerson();    // 随机生成Boy或Girl
        }
        for (int i = 0; i < p.length; i++) {
            p[i].eat();
        }
    }
}
【运行结果】:
Person.eat()
Person.eat()
Person.eat()
Person.eat()

结论:
观察结果,对于静态方法而言,不管父类引用指向的什么子类对象,调用的都是父类的方法。

方法绑定的总结

  • 静态方法: 静态方法看父类
  • 非静态方法:非静态方法看子类
    test link ajalah
    test link ajalah  2019-10-06, 16:27

    Hello! I could have sworn I've been to this blog before
    but after reading through some of the post I realized it's new to
    me. Anyways, I'm definitely delighted I found it and I'll be bookmarking and checking back frequently!

    ทางเข้าfun88
    ทางเข้าfun88  2019-10-06, 16:02

    ส่วนการฝากเงินท่านสามารถเงินได้ทุกแบงค์ตลอดเวลา รวมทั้งการถอนเงินนั้นง่ายมากๆไม่มีวันหยุด และก็ค่าใช้สอยใดๆก็ตามทั้งสิ้น ฝาก –
    ถอน ง่ายๆติดต่อได้ 24 ชั่วโมงน่าไว้ใจได้
    จำต้องเว็บแค่นั้น ที่พร้อมดูแลคุณตลอดทางการเดิมพัน ซึ่งหากอยากหาและมองเห็นความเชื่อใจแล้ว ต้องบอกเลยว่า นั้นน่าไว้ใจเป็นอันมากสำหรับเพื่อการพนันแล้ว สมัคร แทงบอลFUN88 ซึ่งรับประกันเลย ว่าจะไม่ทำให้คุณผิดหวังอย่างแน่แท้นะครับ ค้ำประกันได้เลย แนะนำ เว็บแทงบอล
    Copy

    backpack charms
    backpack charms  2019-10-06, 15:18

    No matter if some one searches for his necessary thing, thus
    he/she wants to be available that in detail,
    therefore that thing is maintained over here.

    online shop kosmetik
    online shop kosmetik  2019-10-06, 14:44

    you're really a just right webmaster. The website loading speed is amazing.
    It seems that you're doing any unique trick. Furthermore, The contents are
    masterpiece. you've done a great task in this matter!

    http://vanminhld.com/category/eyelash-extension/

    Have you ever considered about including a little bit more than just your articles?
    I mean, what you say is valuable and all. However just imagine if you added some great
    pictures or video clips to give your posts more, "pop"!
    Your content is excellent but with pics and video clips, this site could undeniably be
    one of the best in its field. Very good blog!

    Core Java Development
    Core Java Development  2019-10-06, 13:50

    It's amazing to pay a visit this web page and reading the views of all mates
    on the topic of this article, while I am also eager of getting familiarity.

    buy counterfeit money online
    buy counterfeit money online  2019-10-06, 13:13

    It's really a nice and useful piece of information. I am glad that
    you just shared this helpful information with us.
    Please keep us informed like this. Thank you for sharing.

    where to buy fake money
    where to buy fake money  2019-10-06, 12:23

    My brother recommended I may like this website. He was once totally right.
    This publish truly made my day. You cann't consider just how
    much time I had spent for this info! Thanks!

    http://iyapoker.bravesites.com
    http://iyapoker.bravesites.com  2019-10-06, 10:44

    Hmm it appears like your website ate my first comment (it was extremely
    long) so I guess I'll just sum it up what I had written and say,
    I'm thoroughly enjoying your blog. I as well am an aspiring blog blogger but I'm
    still new to the whole thing. Do you have any tips and hints for rookie blog writers?
    I'd genuinely appreciate it.

    best radar detector
    best radar detector  2019-10-06, 09:18

    Hey There. I found your weblog the usage of msn. That is an extremely well written article.
    I will be sure to bookmark it and come back to read more of
    your useful information. Thank you for the post. I will certainly return.

    대구오피
    대구오피  2019-10-06, 09:16

    Very descriptive post, I liked that bit. Will there be a part 2?

    mega casino no deposit bonus 2016
    mega casino no deposit bonus 2016  2019-10-06, 08:48

    She was they make one to be able to that jackpot's numbers.
    You can take advantage of Xzotto 1 of 2 ways. There you have, your
    current 3 approaches to win the lotto. There were no one jackpot winners for this drawing. http://elitanaroda.unas.cz/guest/kniha.php

    918kiss free credit
    918kiss free credit  2019-10-06, 08:16

    Blackberry has got an impressive lineup of devices under its hood.
    Most of them which are very high in demand are those like Blackberry storm, Pearl,
    Curve, Curve flip, Tour etc. Then there's the playbook as well as a 7-inch tablet from blackberry.

    They are used on a daily basis for utilizing various applications and even communicate with some other.
    Though these devices are classified under the category of phones,
    may possibly also used writer's website functions with the use of apps.

    Think concerning your number really carefully.
    How does it audio? How will it look on business cards,
    online? Is it simple to remember? When you are delighted by the new number lock it in by using a confirmation link sent to
    your Gmail subscription. Go back to your Gmail account via an outside browser window, open brand new message and click on the relationship.
    Congratulations! You are now the proud who owns a new telephone value.

    It was previously we'd always be come on top of things enable keep the kids from watching too much television. Now, we ought to keep your
    children occupied so they really won't play too many video
    party games. Apps, shmapps. Let's do something fun! Let's make
    snowflakes.

    Now excitement in learning begins! It is customize how you access
    brand new number. For example, do you want to place
    calls from personal computer Web browser or using
    your cell some of the? Do you want text messages sent to your cell phone when someone
    leaves information on larger Google Voice number? Do you want to
    hear recorded messages via your digital mail? All of these and more possibilities
    exist under tips Phone menu bar inside your Gmail Google Voice
    record.

    The countdown was started around the 49 billion 918kiss
    pc download mark on April 29, according to the official rule page from Apple and took a little over longer to get
    the milestone see.

    Just subscribing to the app, you get a $5 bar tab that lets you send out five
    drinks to either your friends or yourself for release.
    If any of your friends registers for the app, you instantly
    get a $10 bar tab. Diet and exercise add money to your bar tab, just check out
    the "My Account" tab on the webpage. Bartab accepts Visa or MasterCard.

    Until there real benefit apps for Android, and right there happens to
    be not, iOS will continue to dominate on apps, including app manufacturing.

    Not Android, not Google. Not the poor Android app developers.

    pengeluaran togel online
    pengeluaran togel online  2019-10-06, 07:25

    I'm not sure why but this web site is loading incredibly slow for me.
    Is anyone else having this issue or is it a issue on my end?

    I'll check back later and see if the problem still exists.

    red dead 2 apk
    red dead 2 apk  2019-10-06, 06:16

    For most up-to-date news you have to go to see world-wide-web and on the web I found this web site as a best web site for hottest updates.

    실시간온라인카지노
    실시간온라인카지노  2019-10-06, 05:06

    You should take part in a contest for one of the highest quality sites on the net.
    I'm going to highly recommend this site!

    https://seogiare.vn/
    https://seogiare.vn/  2019-10-06, 03:57

    Thanks for finally talking about >java继承 - 我的博客

    play8oy
    play8oy  2019-10-06, 01:43

    It is a psychological name used to mirror ann individual's overall appraisal and evaluation in some merit.
    You use fortunately quality raaw material and make a perfect product.
    It is always his will use the printer be attempted.

    seo services
    seo services  2019-10-06, 01:27

    This might not sound right, since domain has been sitting there inactive for 10 years
    and void of content, but we've got to remember that we are dealing with an algorithm,
    and Google has devised these variables being efficient,
    and oftentimes which means working from generalizations that may include some
    special cases. The SEO basics for small business owners
    are merely a similar for virtually any global business, barring a
    number of focused changes. In spite of all this, blogging remains just about the most
    effective ways to brand your business online.

    tekken 7 apk
    tekken 7 apk  2019-10-06, 01:15

    I was suggested this web site by my cousin. I'm not sure whether this post is written by him as nobody else
    know such detailed about my difficulty. You're wonderful!
    Thanks!