"Simple Java" Java is how to handle aliases (aliasing)

Source: Internet
Author: User

What is a Java alias (aliasing)

Aliases mean that there are multiple aliases pointing to the same location, and that the aliases have different types.

In the following code example, A and B are two different names, with different types A and b,b inheriting a

New b[10= b;a[new  A (); b[0].methodparent ();

In memory, they point to the same location, as follows:

This location in memory is pointed at both A and B, and during run time, the invocation of the method is determined by the object that is actually stored.

How Java handles alias issues

If you copy the following code into your browser, you will find that there is no compilation error,

 PackageSimplejava;classA { Public voidmethodparent () {System.out.println ("Method in Parent"); }}classBextendsA { Public voidmethodparent () {System.out.println ("Override method in child"); }     Public voidMethodchild () {System.out.println ("Method in Child"); }} Public classQ20 { Public Static voidMain (string[] args) {b[] B=NewB[10]; A[] a=b; a[0] =NewA (); b[0].methodparent (); }}

But when you run the above code, the result is the following error message:

Exception in thread "main" Java.lang.ArrayStoreException:simplejava. A
At Simplejava. Q20.main (q20.java:24)

The reason is because Java is processing aliases during run time, knowing that the first element should be a B object, not a a object, during run time.

Therefore, if the code changes to resemble the following, it will run successfully:

New b[10= b;a[new  B (); b[0].methodparent ();

Results Print:

Override method in child

Link: http://www.programcreek.com/2012/12/how-does-java-handle-aliasing/

"Simple Java" Java is how to handle aliases (aliasing)

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.