Home  >  Article  >  Java  >  Java Casting Examples: Up or Down Casting

Java Casting Examples: Up or Down Casting

PHPz
PHPzOriginal
2017-03-12 15:40:261771browse

This article mainly introduces the detailed explanation and simple examples of Java transformation (up or down transformation). Friends who need it can refer to it

type conversion is often encountered in Java programming , object type conversion mainly includes upward transformation and downward transformation.

Upward transformation

We often say this in reality: This person can sing. Here, we don’t care whether the person is black or white, an adult or a child, which means we prefer to use the abstract concept “person”. For another example, a sparrow is a type of bird (a subtype of bird), and a bird is a type of animal (a subtype of animal). We often say this in reality: sparrows are birds. These two statements are actually the so-called upward transformation. In layman's terms, it means the transformation of a subclass into a parent class. This is also in line with the abstract-oriented programming ideas advocated by Java. Look at the following code:


package a.b; 
public class A { 
public void a1() { 
    System.out.println("Superclass"); 
} 
}

Subclass B of A:

package a.b; 
public class B extends A { 
public void a1() { 
    System.out.println("Childrenclass"); //覆盖父类方法 
} 
    public void b1(){} //B类定义了自己的新方法 
}

Class C:

package a.b; 
public class C { 
public static void main(String[] args) { 
    A a = new B(); //向上转型 
    a.a1(); 
} 
}

If run C, is the output Superclass or Childrenclass? Not the Superclass you originally expected, but the Childrenclass. This is because a actually points to a subclass object. Of course, you don't have to worry, the Java virtual machine will automatically and accurately identify which specific method should be called. However, due to upward transformation, the a object will lose methods different from the parent class, such as b1(). Some people may ask: Isn't this unnecessary? We can definitely write like this:


B a = new B(); 
a.a1();

Indeed! But this loses the abstraction-oriented programming features and reduces scalability. In fact, not only that, upward transformation can also reduce the programming workload. Let’s look at the following display class Monitor:

package a.b; 
public class Monitor{ 
public void displayText() {} 
public void displayGraphics() {} 
}

LCD Monitor class LCDMonitor is a subclass of Monitor:


##

package a.b; 
public class LCDMonitor extends Monitor { 
public void displayText() { 
    System.out.println("LCD display text"); 
} 
public void displayGraphics() { 
    System.out.println("LCD display graphics"); 
} 
}

Cathode ray tube display class CRTMonitor Naturally, it is also a subclass of Monitor:

package a.b; 
public class CRTMonitor extends Monitor { 
public void displayText() { 
    System.out.println("CRT display text"); 
} 
public void displayGraphics() { 
    System.out.println("CRT display graphics"); 
} 
}

Plasma display PlasmaMonitor is also a subclass of Monitor:


##

package a.b; 
public class PlasmaMonitor extends Monitor { 
public void displayText() { 
    System.out.println("Plasma display text"); 
} 
public void displayGraphics() { 
    System.out.println("Plasma display graphics"); 
} 
}

Now there is a MyMonitor class. Assuming there is no upward transformation, the MyMonitor class code is as follows:

package a.b; 
public class MyMonitor { 
public static void main(String[] args) { 
    run(new LCDMonitor()); 
    run(new CRTMonitor()); 
    run(new PlasmaMonitor()); 
} 
public static void run(LCDMonitor monitor) { 
    monitor.displayText(); 
    monitor.displayGraphics(); 
} 
public static void run(CRTMonitor monitor) { 
    monitor.displayText(); 
    monitor.displayGraphics(); 
} 
public static void run(PlasmaMonitor monitor) { 
    monitor.displayText(); 
    monitor.displayGraphics(); 
} 
}

Maybe you have realized that the above code has a lot of duplicate code, and it is not easy to maintain. With upward transformation, the code can be more concise:


package a.b; 
public class MyMonitor { 
public static void main(String[] args) { 
    run(new LCDMonitor());           //向上转型 
    run(new CRTMonitor());           //向上转型 
    run(new PlasmaMonitor());      //向上转型 
} 
public static void run(Monitor monitor) { //父类实例作为参数 
    monitor.displayText(); 
    monitor.displayGraphics(); 
} 
}

We can also use the

interface

method, for example:

package a.b; 
public interface Monitor { 
abstract void displayText(); 
abstract void displayGraphics(); 
}
Slightly modify the liquid crystal display class LCDMonitor:

package a.b; 
public class LCDMonitor implements Monitor { 
public void displayText() { 
    System.out.println("LCD display text"); 
} 
public void displayGraphics() { 
    System.out.println("LCD display graphics"); 
} 
}

The modification methods of the CRTMonitor and PlasmaMonitor classes are similar to those of LCDMonitor, but MyMonitor does not need to be modified at all.


It can be seen that upward transformation reflects the polymorphism

of the

class and enhances the simplicity of the program.

Downward transformation


The transformation of a subclass into a parent class is an upward transformation, and conversely, the transformation of a parent class into a subclass is a downward transformation. However, downward transformation may cause some problems: we can say that a sparrow is a bird, but we cannot say that a bird is a sparrow. Consider the following example:


Class A:

package a.b; 
public class A { 
void aMthod() { 
    System.out.println("A method"); 
} 
}

Subclass of A B:

package a.b; 
public class B extends A { 
void bMethod1() { 
    System.out.println("B method 1"); 
} 
void bMethod2() { 
    System.out.println("B method 2"); 
} 
}

Class C:

package a.b; 
public class C { 
   public static void main(String[] args) { 
      A a1 = new B(); // 向上转型 
      a1.aMthod();  // 调用父类aMthod(),a1遗失B类方法bMethod1()、bMethod2() 
      B b1 = (B) a1; // 向下转型,编译无错误,运行时无错误 
      b1.aMthod();  // 调用父类A方法 
      b1.bMethod1(); // 调用B类方法 
      b1.bMethod2(); // 调用B类方法 
      A a2 = new A(); 
      B b2 = (B) a2; // 向下转型,编译无错误,运行时将出错 
      b2.aMthod(); 
      b2.bMethod1(); 
      b2.bMethod2(); 
   } 
}

From above From the code, we can draw the conclusion that downward transformation requires the use of

cast

. Run the C program, and the console will output:

Exception in thread "main" java.lang.ClassCastException: a.b.A cannot be cast to a.b.B at 
        a.b.C.main(C.java:14) 
A method 
A method 
B method 1 
B method 2
In fact, the comments after the downward transformation code in bold have already warned you that a runtime error will occur. Why is the downward transformation code in the first sentence OK, but the code in the second sentence is wrong? This is because a1 points to an object of subclass B, so of course the instance object b1 of subclass B can also point to a1. And a2 is a parent class object, and the subclass object b2 cannot point to the parent class object a2. So how can I avoid a runtime ClassCastException when performing a downcast? Just use the instanceof learned in Section 5.7.7. Let’s modify the code of class C:

A a2 = new A(); 
if (a2 instanceof B) { 
B b2 = (B) a2; 
b2.aMthod(); 
b2.bMethod1(); 
b2.bMethod2(); 
}

After processing in this way, we don’t have to worry about ClassCastException during type conversion.

The above is the detailed content of Java Casting Examples: Up or Down Casting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn