Download Java and java Official Website
Java does not write inherited classes. By default, the standard base class Object is inherited.
Each class can contain a main () Static Method for unit testing.
Inheritance is the reuse of classes. The function uses super to call the same method of the base class and distinguish recursion.
You can add new methods to a derived class to expand the base class.
Code:
/*** Inherit * <p/> * Created by wang on 15/8/7. */class Cleaner {private String s = "Cleaner"; public static void main (String [] args) {Cleaner x = new Cleaner (); x. dilute (). apply (). scrub (); System. out. println (x);} public void append (String a) {s + = a;} public Cleaner dilute () {append ("dilute"); return this ;} public Cleaner apply () {append ("apply"); return this;} public Cleaner scrub () {append ("scrub"); return this ;} @ Override public String toString () {return s ;}} class Detergent extends Cleaner {public static void main (String [] args) {Detergent d = new Detergent (); (Detergent) d. dilute (). apply ()). scrub (). foam (); System. out. println (d) ;}@ Override public Detergent scrub () {append ("Detergent: scrub ()"); super. scrub (); return this;} public Detergent foam () {append ("foam"); return this ;}} public class Disinfectant extends Detergent {public static void main (String [] args) {Disinfectant d = new Disinfectant (); (Disinfectant) d. dilute (). apply ()). scrub (). sterilize (); System. out. println (d); Detergent. main (args); Cleaner. main (args) ;}@ Override public Disinfectant scrub () {append ("Disinfectant: scrub ()"); super. scrub (); return this;} public Disinfectant sterilize () {append ("sterilize"); return this ;}/ *** Output: Cleaner dilute apply Disinfectant: scrub () detergent: scrub () scrub sterilize Cleaner dilute apply Detergent: scrub () scrub foam Cleaner dilute apply scrub */
In inheritance, the constructor with parameters must be called first (super) in the export class; otherwise, an error is returned.
/*** Parameter-based constructor * <p/> * Created by wang on 15/8/8. */class Game {Game (int I) {System. out. println ("Game Constructor:" + I) ;}} class BoardGame extends Game {BoardGame (int I) {super (I); System. out. println ("BoardGame Constructor:" + I) ;}} public class Chess extends BoardGame {public Chess () {super (11); System. out. println ("Chess Constructor"); // super (11); // error} public static void main (String [] args) {new Chess ();}} /*** error: super must be the first statement in the constructor */
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.