Thinking in Java notes (seventh reuse Class)

Source: Internet
Author: User

Seventh re-use class

reusing code is one of the many compelling features of Java, but to be a revolutionary language, it is not enough to simply copy and change the code, and it must be able to do more.

Everything in Java is carried out around the class. By creating a new class, you do not have to start writing again. The trick to this approach is to use classes without breaking existing program code. There are two code reuse mechanisms in this chapter to achieve this goal:

    1. You only need to build an object of the existing class in the new class. Because the new class is made up of objects of existing classes, this method is usually a combination . This method simply re-uses the existing program code functionality, rather than the formal and previous classes have similarities.
    2. The second method is more nuanced, and it creates a new class according to the type of the existing class. Instead of changing the form of an existing class, take the form of an existing class and add new code to it. This approach becomes inherited . Inheritance is one of the cornerstones of object-oriented.
7.1 Combination Syntax

The composition syntax requires only the object reference to be placed in the new class. For example, suppose you need a new type now, where you need multiple string objects, several basic data types, and an object of another class. You can define a new type as follows:

class Apple {    private String s;    Apple() {        System.out.println("Apple()");        s = "Constructed";    }    public String toString() {        return s;    }}public class Desk {    private String s1, s2, s3;    private Apple apple1;    private int appleCount;    private float deskHeight;}

In the example above, the newly created class Desk employs a combination of syntax, reuses part of the code, and combines 3 string data, 2 base type data, and a reference to a class.

7.2 Inheritance Syntax

Inheritance is an integral part of all OOP languages and the Java language. When a class is created, it is always inherited, so it is implicitly inherited from the standard root class Object of Java, unless it is explicitly stated to inherit from another class.

Unlike the composition syntax, inheritance requires the keyword extends to declare "old classes similar to the new class." When you do this, all the fields and methods in the base class are automatically obtained. For example:

class Pet {    private String s = "The pet is ";    public void append(String a) {        s += a;    }    public void toString() {        return s;    }}public class Dog extends Pet {    public void bark() {        System.out.println("woo...");    }    public static void main(String[] args) {        Dog d = new Dog();        d.append("dog");        System.out.println(d.toString());        d.bark();    }}

In the above example, the dog inherits the Pet class and obtains the pet domain and method.

7.2.1 Initializing a base class

Inheritance is not just an interface for copying a base class. When you create an object that exports a class, the object contains a child object of a base class. This self-object is the same as the object created directly from the base class. The difference is that the latter comes from outside, while the child objects of the base class are contained within the exported class object.

It is also critical that the child objects of the base class be in the exported class, and the constructor of the base class is called in the constructor of the exported class to perform initialization, and Java automatically inserts a call to the base class constructor in the constructor of the exported class. For example:

class Animal {Animal() {    System.out.println("Animalss...");}Animal(int a) {    System.out.println(a);}}class Pet extends Animal {Pet() {    System.out.println("Pet...");}Pet(int a) {    System.out.println(a);}}public class JavaTest extends Pet{JavaTest(int a) {    System.out.println("JavaTest...");}public static void main(String[] args) {    JavaTest jt = new JavaTest(1);    }}输出结果为: Animalss...Pet...JavaTest...

As you can see from the above results, the Java compiler will automatically call the default constructor for the base class, and if you want to initialize the inner base class through a different constructor, you can call it through the super () method. The build process spreads from the base class "outward", calling the construction method of the base class at the beginning, and then gradually invoking the constructor of the exported class.

7.3 Agents

The agent does not have direct support in Java, it is the middle of the middle between inheritance and composition. Agent This thing also needs detailed understanding, in the back will study alone, to organize a blog.

7.4.2 Name Masking

The base class in Java has a method name that has been overloaded multiple times, and redefining the method name in the export class does not mask any version in the base class. For example:

class BClass {public void func() {    System.out.println("1...");}public void func(int i) {    System.out.println("2...");}public void func(String s) {    System.out.println("3...");}}class SClass extends BClass {public void func(float a) {    System.out.println("6...");}}public class JavaTest{public static void main(String[] args) {    SClass s = new SClass();    s.func(1f);    s.func();    s.func("");}}运行结果为:6...1...3...

The method name is overloaded again in the inheriting class, but the methods that are overloaded in the previous subclass are still there.

7.7 Upward transformation

In Java inheritance, the relationship between the base class and the exported class can be summed up as "The export class is a type of the base class." For example, there is a base class for the instrument named Instrument and an export class named Wind. Because inheritance ensures that all methods in the base class are equally valid in the exported class, all the information that can be sent to the base class can also be sent to the export class. Look at the following example:

class Instrument {    public void play() {}    static void tune(Insatument i) {        // ...        i.play();    }}public class Wind extends Instrument {    public static void main(String[] args) {    Wind flute = new Wind();    Instrument.tune(flute);}}

In the above example, the parameters of thetune () method can accept instrument references, but a reference to wind is passed in when called. In the tune method, the program code can work on instrument and all of its exported classes, which translates the exported class reference into a base class reference, which we call an upward transformation . In the process of upward transformation, the only thing that can happen in the class interface is the Lost method. Because it is converted from a more specialized type to a generic type, it is always safe.

7.7.2 re-discussion on combination and inheritance

In object-oriented programming, there is a sentence called "Combinatorial better than inheritance", although inheritance is emphasized many times, it does not mean to use inheritance as much as possible. One of the clearest ways to judge is to ask yourself if you need to move up from a new class to a base class. Inheritance is necessary if it has to be transformed upward. The following will be devoted to writing a blog to seriously think, the combination is better than inheritance this sentence.

7.8 Final keyword

For a description of the final keyword, take it out alone and do a static keyword once to understand, click Enter.

Thinking in Java notes (seventh reuse Class)

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.