Java Inheritance and polymorphism

Source: Internet
Author: User
Tags stub

One

1. Media Database

Package DOME;//CD class public class CD {private string title;//name private string artist;//singer private int numoftracks;// Several songs private int playingtime;//play time private Boolean gotit;//whether to lend private String comment;//Comment//Constructor Initialize object public CD (String Title, string artist, int numoftracks, int playingtime, string comment) {super (); this.title = Title;this.artist = Artist;t His.numoftracks = Numoftracks;this.playingtime = Playingtime;this.comment = comment;} Public  void Print ()//class Output {    System.out.println ("CD:" +title+ "-" +artist);} public static void Main (string[] args) {//TODO auto-generated method stub}}
package Dome;//dvd class public class DVD {private string Title;private string director ;p rivate int Playingtime;private boolean gotit;private string Comment;public DVD (string title, string Director, string com ment, int playingtime) {super (); this.title = Title;this.director = Director;this.playingtime = Playingtime;this.comment = comment;} public void print () {System.out.println ("DVD:" +title+ "-" +director);}} 
Package Dome;import java.util.arraylist;//Media Library public class Datebase {private arraylist<cd> listcd=new ArrayList <CD> ();    Private arraylist<dvd> listdvd=new arraylist<dvd> ();    public void Add (CD CD) {Listcd.add (CD);} public void Add (DVD DVD) {Listdvd.add (DVD);} public void list () {for (CD Cd:listcd) {cd.print ();} for (DVD Dvd:listdvd) {dvd.print ();}} public static void Main (string[] args) {datebase db=new datebase ();d B.add (New CD ("ABC", "ABC", 4, "* * *"));d B.add (New C D ("Def", "Def", 4, "* * *"));d b.add ("xxx", "AAA", "...");d B.add (New DVD ("YYY", "BBB", "..."));        Db.list ();}}

2, the above program has a lot of duplicate code, using the parent class and subclass inheritance, you can extract the public, as a parent class, unique as a subclass, and then use protected or super, to achieve mutual invocation

Parent Class Item Class program

Package Dome;public class Item {protected String title;//changes private to protected so that all subclasses can access the private int playingtime;//Play Time private Boolean gotit;//whether to lend private String comment;//Comment    //constructor to assign initial value public item (int Playingtime, String comment) {super (); this.playingtime = playingtime;this.comment = comment;} Public void Print () {System.out.print (playingtime+ "-" +comment);//This two private is not output in subclasses, the parent class defines the output}public static void Main (string[] args) {//TODO auto-generated method stub}}

Because the two scopes are different, the specific code is not the same.

Private needs to define the constructor in the parent class and initialize it. Use super to pass the value.

Protected does not need to be in the parent class, but this method is relatively unsafe.

Sub-class

package DOME;//CD class public class CD extends item{//inherit itemprivate String artist;//  Singer private int numoftracks;//songs//constructor initialization object public CD (string title, string artist, int numoftracks, int playingtime, string Comment) {super (playingtime, comment); this.title = Title;this.artist=artist;this.numoftracks = Numoftracks;} public void print ()//class output  {System.out.print ("CD:" +title+ "-" +artist+numoftracks+ "-");//Direct Output super.print ();//Call parent class output System.out.println ("\ n") ;} public static void Main (string[] args) {//TODO auto-generated Method stub}} 
Package Dome;public Class DVD extends item {//Inherit Itemprivate string director;//Director public DVD (string title, string director, String comment, int playingtime) {super (playingtime,comment); this.title = Title;this.director = Director;} Public void Print () {System.out.print ("DVD:" +title+ "-" +director+ "-");//Only title,director can output super.print () ;//Call PRINTSYSTEM.OUT.PRINTLN ("\ n") of the parent class;}}

Main program

Package Dome;import Java.util.arraylist;public class Datebase {private arraylist<item> listitem=new ArrayList <item> ();//With the parent class public    void Add (item i) {Listitem.add (i);} public void list () {for(item i:listitem) {I.print ()}} public static void Main (string[] args) {datebase db=new datebase ();d B.add (New CD ("ABC", "ABC", 4, 60, "* * *"));//originally DB Add is Item, where the subclass object is assigned to the parent class variable, the Db.add (New CD ("Def", "Def", 4, "* *"));d b.add ("xxx", "AAA", "...");d B.add (new DVD ("yyy", "BBB", "...");                Db.list ();}}

Note again that the print () constructor, because of the uniqueness of the subclass output, always constructs the output function in the subclass,

There are print output functions in both the parent and child classes, and the runtime chooses the appropriate function based on the variable type (ITEM,CD,DVD). This is called polymorphism.

Two

2.1

In fact, it is defined that a parent class will be able to extract all the common, and then subclass when the parent class runs, simplifying duplicate code.

Package Hello;import Java.util.arraylist;import Java.util.hashset;public class Test {public static void main (string[] args) {String s = "Hello"; s= "HI"; System.out.println (s);}}

You can see that the object of S is "Hello" when id=19;

When the object is Hi, you can see that it is not the hi that id=23 the hello, but s pointing to the new object.

2.2

Notice the difference between the variable and the object. A variable simply declares a name, and the object is new initializes a value,

The object of the parent class cannot be assigned to a variable of the child class

The object of the subclass can be assigned to a variable of the parent class.

The debug program is as follows

After 22 lines run, the following results are obtained

After 23 lines have finished running

After 24 lines have finished running

It and the CD point to the same object.

For basic data types called type conversions, the object is called styling.

Three, polymorphic

The appropriate function is automatically called based on the type of the variable.

Four

Function of Object

4.1 toString ()

Using the ToString () function output of object

Modify Item

Package Dome;public class Item {Protected String title;//changes private to protected so that all subclasses can access the private int playingtime;/ /Play Time Private Boolean gotit;//whether to lend private String comment;//Comment    //constructor to assign initial value public item (int playingtime, String comment) {super (); this.playingtime = playingtime;this.comment = comment;} public void print () {System.out.print (playingtime+ "-" +comment);//The two private is not output in subclasses, the parent class defines output}@Overridepublic String toString () {//return "Item [title=" + title + ", playingtime=" + Playingtime + ", gotit=" + Gotit + ", comment=" + Comment//+ ", toString () =" + super.tostring () + "]", Return playingtime+ "-" +comment;} public static void Main (string[] args) {//TODO auto-generated method stub}}

Modify CD

Package DOME;//CD class public class CD extends item{//inheritance itemprivate String artist;//singer private int numoftracks;//several songs// Constructor initialization object public CD (string title, string artist, int numoftracks, int playingtime, string comment) {super (Playingtime, comm ENT); this.title = Title;this.artist=artist;this.numoftracks = Numoftracks;} public void print ()//class Output {System.out.print ("CD:" +title+ "-" +artist+ "-" +numoftracks+ "-");//Direct Output super.print ();//Call Parent class Output System.out.println ("\ n");}@Overridepublic String ToString () {//return "CD: [artist=" + artist + ", numoftracks=" + Numoftracks + ", tostring () =" + super.tostring () + "]"; return "CD:" +title+ "-" +artist+ "-" +numoftracks+ "-" +super.tostring ();}public static void Main (string[] args) {//TODO auto-generated method Stub CD cd=new CD ("abc", "Def", 4,60, "good"); Cd.print ();//Call the print () function output System.out.println (CD);//Call the ToString () function, but need to modify the output format yourself}}

4.2

Package Dome;public Class DVD extends item {//Inherit Itemprivate string director;//Director public DVD (string title, string director, String comment, int playingtime) {super (playingtime,comment); this.title = Title;this.director = Director;} public void print () {System.out.print ("DVD:" +title+ "-" +director+ "-");//Only title,director can output super.print ();// Call the parent class's printSystem.out.println ("\ n");} public static void Main (string[] args) {DVD dvd=new DVD ("xxx", "AAA", "...",);D VD dvd1=new DVD ("xxx", "AAA", "...");D V D Dvd2;dvd2=dvd; System.out.println (Dvd.equals (DVD1));//Call the EqualsSystem.out.println of object (Dvd.equals (DVD2));}}

You can see that DVDs and DVD2 are the same, because DVD2 are assigned by DVDs and they work together to manage a location.

The DVD1 is generated from the new initialization, and the location is different.

But here their content is clearly the same, so you need to change the code.

4.3

Package Dome;public Class DVD extends item {//Inherit Itemprivate string director;//Director public DVD (string title, string director, String comment, int playingtime) {super (playingtime,comment); this.title = Title;this.director = Director;} public void print () {System.out.print ("DVD:" +title+ "-" +director+ "-");//Only title,director can output super.print ();// Call the parent class's printSystem.out.println ("\ n");} @Overridepublic boolean equals (Object obj) {//TODO auto-generated method Stub//return super.equals (obj);D VD dvd= ( DVD) obj;//down styling return director.equals (dvd.director);//director Same}public static void Main (string[] args) {DVD Dvd=new DVD ("xxx", "AAA", "...",;D VD dvd1=new DVD ("xxx", "AAA", "...");D VD Dvd2;dvd2=dvd; System.out.println (Dvd.equals (DVD1));//Call the EqualsSystem.out.println of object (Dvd.equals (DVD2));}}

@Override indicates that the following function is a function that overrides the parent class (the function of object), the function header is fixed and cannot be modified.

  

  

  

  

  

  

  

  

  

  

Java Inheritance and polymorphism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.