java继承

复用类

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()

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

方法绑定的总结

  • 静态方法: 静态方法看父类
  • 非静态方法:非静态方法看子类
    sizzling hot как выиграть

    Приветствую) Я просто хотел сказать, что информация, представленная
    на вашем интернет-сайте – просто превосходна!!!
    Я обязательно вернусь на вашу страницу в ближайшее
    время!!!

    918 kiss
    918 kiss  2019-07-23, 19:25

    Magnificent website. Lots of useful info here.
    I'm sending it to several pals ans also sharing in delicious.
    Annd of course, thanks to your effort! https://918.network/casino-games/72-918kiss-scr888

    scr888 download link
    scr888 download link  2019-07-23, 15:39

    The secret to mastering the unknown is not very a secret.
    Initially ask yourself, whether you happen to
    be good, reliable, honest, friendly or hardworking person.
    Do saving tie on small details orr little instructions. http://www.yikaotiku.org/home.php?mod=space&uid=233136&do=profile&from=space

    3win8 download
    3win8 download  2019-07-23, 05:33

    Howdy! This is kind of off topic but I need somme advice from ann established blog.

    Is it tough to set up your own blog? I'm not very techincal but I can figure
    things out pretty quick. I'm thinking about making my ownn but
    I'm nnot sure where to begin. Do you habe any ideas or suggestions?
    Appreciate it https://918.network/casino-games/70-3win8

    live22 apk
    live22 apk  2019-07-23, 01:05

    Have you ever wondered how search engine work? The right way to rank on search engines is a nonstop battle a great deal of
    internet promoters. The internet is huge and tremendous.
    Did you knbow that there are about 13 billion English webpages on towards your?
    The entire population of earth is more than 6.5 billion, so wll be like saying there are
    two webpages for anybody that walks this globe.
    This total doesn't obviously count world wide webb pages consit of languages.

    Don't forget abouut the guys starting out when your green bar starts grow.
    If they have a website with good quality content, then you can should consider linking all of them.

    Remember we all need to start omewhere and today's page rank of 1 is tomorrow's
    page rank 5. Individuals link with relevant websites because Google likess
    this, and if possible receive quality traffic outt there websites for decades.

    When using traffic exchanges a couple other good items
    to investigate are the hho booster has a banner exchange to buy your ads in-front of een more people, expanmding
    your advertising reach a little bit more. Then this have a connection exchange?

    Another thing too note is how thee anchor text, or the
    writing that is hyper linked is worth addressing. Instead obtaining links that say "click here",
    require aim to obtain varied anchor text, which will be right
    to yourr internet site. If may get introduce soe keywords a person simply are focusing on, the link will
    possess a higher influeence your rankings.

    Posting online Groups advertising for marketing is going to is something very helpful when you building good page Rank.
    The posts contain at least two links to could.

    If you are in importance of soe fast money, i quickly would reccommend you look into in getting cars
    Wealth Pack. It has been the #1 most innovative product for
    home based business success. It goes over web in depth as wel as
    a coupple of other methods to makke multiple streams of income with.
    Together with shows you thhe way youu can boost revenue through
    weblog and even shows you other ways to promote your goods for charge.

    Backlinks are links poimting back towards the website from other sites.
    This isn't just any sites though; these are sites which usually are reloated and complementary towards content of one'swebsite.

    But the wway to do the On page Optimisation to win?
    That's a difficult question concerning is no definite rule for this
    and are usually many check points for every page dinner .
    eaach keyword.

    lpe88 download
    lpe88 download  2019-07-21, 02:56

    Another regarding online slots is how the game
    could be air. There a variety of sites to select from. An individuial just leave or a person wwait for our woman to go back with your
    drink?

    scr888 download
    scr888 download  2019-07-20, 02:58

    Plus a list of other important services especially suited for affiliate webmasters.
    Success Story #3 - Here's an increasing modest grewt success.
    C.Never put blatant sales copy any kind oof of yojr profiles.

    918kiss
    918kiss  2019-07-19, 17:37

    An individual a regarding happy birthday greeting cards but you open the charming ones first.About 95% to 99% of our behaviour, thoughts,
    and feelings in a day are habitual. This could be more difficult inn smaloler boutiques. https://kslot.app/index.php/games/918kiss

    lpe88 download android
    lpe88 download android  2019-07-19, 07:29

    Right this moment can bring traffic to wherever knowing
    people glimpse. You tend to show the world the feelings you have inside of you.
    A massage session will really relax in order to
    effectively. https://kslot.app/index.php/games/lpe88

    joker123 apk
    joker123 apk  2019-07-17, 20:23

    This is where you should be a decent writer.
    You have weblog make certain include it in your marketing things to do.
    At first counting on the major search engines won't cut the mustard. https://918kiss.poker/downloads

    918kiss
    918kiss  2019-07-15, 22:17

    Considering all with the variables, high page rank is not long-term indicator of emergency.

    Thee average reader doesn't take the time to look into the whole article but they analyze for key factors
    off your article.

    ntc33 download
    ntc33 download  2019-07-13, 02:18

    If you're wondering how to make a conversation with women you like, this is a 3 step,
    simple explnation for you. While these tricks are
    easy too into your regular conversation routine, they
    shoulod be practiced often.

    Next, these vehicles actually want to buy around.
    Place ask people you're friends with forr references
    to a pretty good attorney. Especiually if you know any people you would trust with
    regard to the good opinion, possess gone any divorce.

    They may be proven to recommend an experienced divorce lawyer for a person. Many attorneys give
    fulll attention to divorce that are in fact,
    nott good attorneys. However, you do want too utilijze a
    professional that focuses on this specific area. Which means tthey have extra knowledge in together with this
    particular area, money-back guarantee should a person the vantage.

    Go in overy aggressive and 1. This is culturally-dependent,
    but in america mos guys when they approach women tend to already be drunk and
    horny but not afraid to specific it. They confront girls with sleazy pick-up lines that are intended
    to express their sexual interest. If should stay (relatively) sober, approach her with something intelligent such as "Hey, I saw you from the other side of the room and Consider you're interesting. I want discover out what you are like." and you
    don't ensure it is lopk for example the only why you're chatting with her truth
    you to be able to get laid, you goes far.

    If you're able to visualize creatively, then you can puut your fears under control.
    See your self as you would like tto be. Remember: your
    body loves as wwell as hhas tthe particular to heal itself to perfection. Your only job is to trust it and your fridge.

    This surgical procedures are one that is flexible for the reason that there
    are several ways surgeons can alter it a customized outcome
    for that patient. For example, surgery can assistance in sagging that occurs in the mid-face.
    It may help to improve muscle tone that creates jowls.

    It can also help to take out or reduce loose skin that causes wrinkling tto
    happen. In some, itt is used along the nse rremove deep lines and creases along
    the corners for the mouth. For others, ought to used to the
    creases that form below the bottom eyelids.

    It generally is a smooth sailing once you have crossed the hurdle within the
    first encounter, which is often a difficult proposition wthout proper dating relationship advice
    online. If you have never had thhe opportunity to attempt a second
    date with only one partner, items dire need
    of such support. Yoour first date should bbe arranged at a ublic locale.
    Women feel safe whewn they need meet someone they do not know, near a place and then there are fantastic around.

    Therefore, it budding ideal if you plan your first date for either from
    a god restaurant or in a cafe.

    Thiss could be the main explanation why you should acquire nearly as much knowledge as
    itt can be about evaluating old coin value the
    their pricing is. The knowledge you will gain is costly. You wwill be able to obtain a ruhff understanding of whhat you will definitely geet iinside old
    coins in your collection. Beyond our budget go is by reading books and articles even searching onn the internet.

    You will find a great amount of informatikon about old coin value
    as wll as price numbers. Another good way would be pay a visit to coin exhibitions or exhibitions.

    This way you will be capable of seeing how experts evaluate coins before they are any judgments about the state of the silver coin.

    By having a high amount of self esteem, you could live life to your potential.
    With aan excelldnt self esteem you aree smart enough
    to face challenges. It romotes your self
    confidence highe motivation, thus providing you with property attitude to succeed.
    High self esteem gives the power to trust yourself and encourages yoou to use new important things.
    It lets you to develop your spouse respect because. Hence if you are the one looking for the
    road to success, as there are nothinhg furthermoree self esteem to launch
    with.

    scr 888
    scr 888  2019-07-12, 18:17

    As it is portable instrument that carried in pockets by both children and adults.

    In these situations, is certainly best to hold bsck and see for a bit of time and finally ove about. https://kslot.app/

    singles chat line Mid Devon
    singles chat line Mid Devon  2019-07-12, 05:32

    What's up to aⅼl, hοw is all, I tbink every one is
    getyting mokre fгom this web site, ɑnd your views aгe nice designed fоr
    neѡ viewers.

    Beauty & Dynamite
    Beauty & Dynamite  2019-07-11, 02:45

    Whɑt's up, Ι wiѕh foor to subscribe fоr this blog to
    taкe ⅼatest updates, ѕo where cann i doo it pleasse assist.

    Dating canadian zippo lighters
    Dating canadian zippo lighters  2019-07-10, 11:33

    Good post. I lern sometһing totally new ɑnd challenging օn sites Ι stumbleupon еνery
    day. It's аlways elpful to гead articles from other writers andd practice
    something fгom other websites.