Java beginners (II): upward and downward transformations, and java Transformations

Source: Internet
Author: User

Java beginners (II): upward and downward transformations, and java Transformations

In the course of learning Java, this article is summarized as a summary of the confusion of transformation operations. The example references Java programming ideas.

Directory

Synonyms

Upward transformation and downward Transformation

Example 1: Call the specified parent class method for upward Transformation

Example 2: upward transformation and dynamic binding

Example 3: upward transformation and static binding

Example 4: downward Transformation

Misunderstanding of Transformation

1. Run information (RTTI)

2. array type

3. Java container

 

Synonyms

First, there are several synonyms. They appear in different books, which is one of the reasons for confusion.

Parent/superclass/base class

Subclass/export class/inherit class/derived class

Static binding/pre-binding

Dynamic binding/post-binding/runtime binding

 

Upward and downward transformation Example 1: upward transformation, calling the specified parent class Method
class Shape {
  static void draw(Shape s) { System.out.println("Shape draw."); }}class Circle extends Shape {
  static void draw(Circle c) { System.out.println("Circle draw."); }}public class CastTest { public static void main(String args[]) { Circle c = new Circle(); Shape.draw(c); }}

The output is

Shape draw.

This indicates that the draw (Shape s) method was originally designed to accept the Shape reference, but here it passes the Circle reference. In fact, the draw (Shape s) method can be used to export all Shape classes, which is called upward transformation.Behavior, which is consistent with the category of the method.In other words,Because it is clearly pointed out that it is a parent Shape method, its behavior must be the behavior corresponding to this method, and there is no ambiguity.

The name of "upward transformation" comes from the painting method of the class inheritance graph: the root is placed at the top, and then gradually goes down. In this example, the two classes are used as examples, as shown in:

Example 2: upward transformation and dynamic binding

class Shape {    public void draw() {        System.out.println("Shape draw.");    }}class Circle extends Shape {    public void draw() {        System.out.println("Circle draw.");    }}public class CastTest {    public static void drawInTest(Shape s) {        s.draw();    }    public static void main(String args[]) {        Circle c = new Circle();        drawInTest(c);    }}

The output is

  Circle draw.

The reason for doing so is that a drawInTest (Shape s) can process all the Shape subclasses without having to provide its own methods for each subclass. However, this method can call the methods common to the parent class and subclass, even if the behavior of the two is inconsistentIt only shows the behavior of the corresponding subclass method. This is what polymorphism permits, but is prone to confusion.

Example 3: upward transformation and static binding
class Shape {    public static void draw() {        System.out.println("Shape draw.");    }}class Circle extends Shape {    public static void draw() {        System.out.println("Circle draw.");    }}public class CastTest {    public static void drawInTest(Shape s) {        s.draw();    }    public static void main(String args[]) {        Circle c = new Circle();        drawInTest(c);    }}

The output is

  Shape draw.

What is the difference between Example 3 and Example 2? After a closer look, we can see that the method called in Example 3 is modified by the static method, and different results are obtained.

The two behavior differences are as follows:In Java, except the static method and final method (including the private method), other methods are dynamically bound.For an input base class reference, the later binding can correctly identify the exported class to which it belongs. After static is added, this effect is naturally unavailable.

After understanding this, we can understand why we should write the example one. The code in Example 1 clearly specifies the method for calling the parent class method, and the method used in Example 3 is statically bound, which is not directly specified.

Example 4: downward Transformation

From Section 8.5.2 of Java programming ideology, I made some modifications to demonstrate how to obtain the access method of the unique method of subclass through type conversion.

This is equivalent to telling the compiler additional information, and the compiler will check accordingly.

class Useful {    public void f() {System.out.println("f() in Useful");}    public void g() {System.out.println("g() in Useful");}}class MoreUseful extends Useful {    public void f() {System.out.println("f() in MoreUseful");}    public void g() {System.out.println("g() in MoreUseful");}    public void u() {System.out.println("u() in MoreUseful");}}public class RTTI {    public static void main(String[] args) {        Useful[] x = {            new Useful(),            new MoreUseful()        };        x[0].f();        x[1].g();        // Compile-time: method not found in Useful:        //! x[1].u();        ((MoreUseful)x[1]).u(); // Downcast/RTTI        ((MoreUseful)x[0]).u(); // Exception thrown    }}    

Output

Exception in thread "main" java.lang.ClassCastException: Useful cannot be cast to MoreUseful
at RTTI.main(RTTI.java:44)
f() in Useful
g() in MoreUseful
u() in MoreUseful

  Although x [1] of the Useful type of the parent class receives a reference from a subclass MoreUseful object, you cannot directly call the u () method in its subclass. If you need to call it, you need to perform a downward transformation.This method is common. For example, a common method is that the input parameter to be processed is a parent class. Different logic is used to process the input parameter type information into a corresponding subclass.

In addition,The parent class object cannot be converted down to a subclass object..

The benefits of downward transformation are obvious when you learn interfaces (if you think of implementing interfaces as multiple inheritance ). For more information, see the example in section 9.4:

interface CanFight {    void fight();}interface CanSwim {    void swim();}interface CanFly {    void fly();}class ActionCharacter {    public void fight() {}}class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {    public void swim() {}    public void fly() {}}public class Adventure {    static void t(CanFight x) { x.fight(); }    static void u(CanSwim x) { x.swim(); }    static void v(CanFly x) { x.fly(); }    static void w(ActionCharacter x) { x.fight(); }    public static void main(String[] args) {        Hero i = new Hero();        t(i); // Treat it as a CanFight        u(i); // Treat it as a CanSwim        v(i); // Treat it as a CanFly        w(i); // Treat it as an ActionCharacter    }}

 

Misunderstanding of Transformation

The transformation is very convenient. You can use the transformation to write flexible code. However, if you do what you want to do, you will inevitably fall behind. Below are several situations that seem to be convertible and will actually lead to errors.

1. Run information (RTTI)
/* This sample code is excerpted from section 14.2.2 of Java programming thoughts */Class <Number> genericNumberClass = int. class

This code is invalid and cannot be compiled. Even if int is converted to Integer, it cannot be compiled.Although Integer is a subclass of Number, the Integer Class object is not a subclass of Number Class object.

2. array type
/* Rewrite section 15.8.2 of Java programming ideology in code section. This example has nothing to do with generics. */Class Generic <T >{} public class ArrayOfGeneric {static final int SIZE = 100; static Generic <Integer> [] gia; @ SuppressWarnings ("unchecked ") public static void main (String [] args ){//! Gia = (Generic <Integer> []) new Object [SIZE]; gia = (Generic <Integer> []) new Generic [SIZE] ;}}

Java. lang. ClassCastException is prompted when the annotation is removed. What is confusing here is that,The subclass array type is not a subclass of the parent class array type.. After the exception prompt, you can see

[Ljava.lang.Object; cannot be cast to [LGeneric;

In addition to the exception information output through the console, you can use the following code to see what type of gia is:

        Object[] obj = new Object[SIZE];        gia = (Generic<Integer>[]) new Generic[SIZE];        System.out.println(obj.getClass().getName());        System.out.println(gia.getClass().getName());        System.out.println(obj.getClass().getClass().getName());        System.out.println(gia.getClass().getSuperclass().getName());

Console output:

[Ljava.lang.Object;
[LGeneric;
java.lang.Object
java.lang.Object

Visible,The gia and obj defined by Generic <Integer> [] gia and Object [] obj have no inheritance relationships. Naturally, they cannot be converted into types, whether or not the object in this array is a subclass object.(Subclass objects can be obtained through upward transformation. If the object to be converted is actually a subclass object, see Example 4)

3. Java container
/* Code Excerpt from Java programming thoughts section 15.10 */class Fruit {} class Apple extends Fruit {} class Orange extends Fruit {} public class Test {public static void main (String [] args) {// unable to compile List <Fruit> fruitList = new ArrayList <Apple> ();}}

Clearly, the Fruit List can store Apple objects. Why does the assignment fail? In fact, this is not an upward transformation. Although you can use getClass (). getName () indicates that List <Fruit> and List <Apple> belong to java. util. the ArrayList type. However, if it can be compiled here, it is unreasonable to allow the ArrayList <Apple> to store an Orange object.Although ArrayList <Fruit> and ArrayList <Apple> are of the same type during runtime due to generic erasure, the specific element types that can be held are checked during compilation.

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.