Java语言规范第五/六章-数据类型转换/名称

本文介绍了Java语言规范中关于数据类型转换和名称的部分。在数据类型转换过程中,例如从int到float,可能会导致精度丢失。同时,文章通过示例展示了byte到char的扩展和收缩转换。此外,当不同包或子包中存在同名类时,如`Vector`,会导致命名冲突。在接口实现时,若两个接口包含相同常量,会导致编译错误。在继承中,非public或protected的方法不能被子类覆盖,否则会引发变异错误。最后,文章提醒了在方法访问权限不当时可能导致的无限递归问题及其后果。
摘要由CSDN通过智能技术生成

Java语言规范第五章-数据类型转换(Java Language Specification – Chapter5 Conversions)

Java语言规范第六章-名称(Java Language Specification – Chapter6 Names)

 

int big = 1234567890;

float approx = big;

System.out.println(approx);// 1.23456794E9

System.out.println((int) approx);// 1234567936

在从int转换为float的过程中,数据发生了精度丢失。

 

下面的转换组合了扩展和收缩两种转换:

byte to char

首先byte被转换为int(扩展),然后再由int转换为char(收缩)


import java.util.*;

class Vector {

int val[] = { 1 , 2 };

}

class Test {

    public static void main(String[] args) {

        Vector v = new Vector();

        System.out.println(v.val[0]);//1

    }

}

java.util.Vector会被屏蔽掉。

 

package vector;

public class Vector { Object[] vec; }

由于vector包已经包含了一个Vector类,所以它不能在包含一个名为Vectorsubpackage

 

构造器和类型变量不是成员。

 

interface Colors {

    int WHITE = 0, BLACK = 1;

}

 

interface Separates {

    int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;

}

 

class Test implements Colors, Separates {

    public static void main(String[] args) {

        System.out.println(BLACK); // compile-time error: ambiguous

    }

}

 

BLACK是歧义的 ,必须适应full qualified name来进行确定。

 

java.lang.Object:

    public final native Class<?> getClass();

jsr.TestInterface:

    public final Class<?> getClass();//modifier final not allowed here

    public Class<?> getClass();//cannot override getClass() in java.lang.Object;overriden method is final.

 

package jsr901;

public class Point {

    public int x,  y;

    void move(int dx, int dy) {

        x += dx;

        y += dy;

    }

    public void moveAlso(int dx, int dy) {

        move(dx, dy);

    }

}

 

package jsr901.sub;

public class PlusPoint extends jsr901.Point {

    public void move(int dx, int dy) {

        super.move(dx, dy);// compile-time error

        //move(int,int) is not public in jsr901.Point, can not be accessed from outside package

        moveAlso(dx, dy);

    }

}

由于在父类中没有将move定义为public或者protected,所以子类不会覆盖父类的move方法,而在调用super方法时也会发生变异错误。

如果将super.move(dx,dy)一行删除,执行下面的测试程序,程序可以正常运行,因为子类并未覆盖父类的方法,所以只是单纯的运行子类的方法:

package jsr901.sub;

class TestPoint {

    public static void main(String[] args) {

        PlusPoint pp = new PlusPoint();

        pp.move(1, 1);

        System.out.println("END");

    }

}

如果将父类中的move修改为protected或者public,那么由于调用过程是无限循环,所以将导致:Exception in thread "main" java.lang.StackOverflowError

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值