Java Programming Ideas Fourth Edition * Chapter seventh * Personal Exercises

Source: Internet
Author: User
Tags class manager

Exercise 1: (2) Create a simple class. In the second class, a reference is defined as the object of the first class. Use lazy initialization to instantiate this object.

Package Test;public class Manager {public static void main (String args[]) {Second s=new Second (); S.getfirst ();} /** * Printed result: */}class first{}class Second{first F; Second () {System.out.println ("Creating Second");} First lazy () {if (f==null) {System.out.println ("Creating first"); F=new first ();} return F;} Public first GetFirst () {return lazy ();}}

Exercise 2: (2) inherit from detergent to produce a new class. Overwrite scrub () and add a new method named Sterilize ().

Package Test;public class Manager {public static void main (String args[]) {Sub S=new sub (); S.apply (); S.dilute (); S.foam (); S.scrub (); S.sterilize (); new print (s);} /** * Print Result: Cleanser apply () dilute () foam () Sub.scrub detergent.scrub () sub.sterilize () */}class print{print (Object obj) { System.out.println (obj);}} Class Cleanser{private string s= "cleanser";p ublic void Append (String a) {s+=a;} public void Dilute () {Append ("dilute ()");} public void Apply () {Append ("Apply ()");} public void Scrub () {Append ("scrub ()");} Public String toString () {return s;} public static void Main (string[] args) {Cleanser X=new Cleanser (); X.dilute (); x.apply (); X.scrub (); new print (x);}} Class Detergent extends cleanser{public void scrub () {Append ("Detergent.scrub ()");} public void Foam () {Append ("foam ()");}} Class Sub extends detergent{public void scrub () {Append ("Sub.scrub"); Super.scrub ();} public void sterilize () {Append ("sub.sterilize ()");}}


Java Programming Ideas Fourth Edition * Seventh * personal exercise

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.