精华内容
下载资源
问答
  • java核心技术 第11版 英文版, java核心技术 第11版 英文版。
  • java核心技术 第11版 英文版 卷2
  • java核心技术第11版中文版的1,2卷的pdf</p>
  • Prentice.Hall.Core.Java.Volume.II.Advanced.Features.11th.Edition.pdf Java核心编程第11版pdf,全网最新
  • } } 受访问保护 若希望限制超类中某个方法 只允许子类访问, 或访问某个字段, 使用关键字protected java中保护字段只能由同一个包的类访问 Object: 所有类的超类 java中每个类都扩展了超类 Object类型变量 可以...

    类、超类和子类

    例如员工只有标准工资, 而经理有工资加奖金,
    Manager和Employee之间存在明显的“is-a”关系

    定义子类

    使用关键字extends表示继承

    public class Manager extends Employee
    {
    	add methods and fields
    }
    

    构造的新类诞生与一个已存在的域(超类(superclass), 基类(base class)或父类(parents class)), 新类称为子类(subclass), 派生类(derived class)或孩子类(child class)。

    public class Manager entends Employee
    {
    	private double bonus;
    	...
    	public void setBonus(double bonus)
    	{
    		this.bonus = bonus;
    	}
    }
    

    覆盖方法

    超类中有些方法对子类并不一定适用, 需要提供新的方法来覆盖(override)

    public class Manager extends Empolyee
    {
    	...
    	public double getSalary()
    	{
    		...
    	}
    	...
    }
    

    若希望在覆盖方法之中调用超类的同名方法, 使用关键字super

    public double getSalary()
    {
    	double baseSalary = super.getSalary();
    	return baseSalary + bonus;
    }
    

    子类构造器

    public Manager(String name, double salary, int year, int month, int day)
    {
    	super(name, salary, year, month, day);
    	bonus = 0;
    }
    

    如果子类没有显式调用超类的构造器, 将自动调用超类的无参数构造器
    一个对象变量可以指示多种实际类型的现象称为多态(polymorphism), 运行时自动选择适当的方法, 称为动态绑定(dynamic binding)。
    inheritance/ManagerTest.java

    package inheritance;
    
    /**
     * This program demonstrates inheritance
     * @author Cay Horstmann
     */
    
    public class ManagerTest {
        public static void main(String[] args)
        {
            //construct a Manager object
            var boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
            boss.setBonus(5000);
            var staff = new Employee[3];
    
            //fill the staff array with Manager and Employee objects
    
            staff[0] = boss;
            staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
            staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
    
            //print out information about all Employee objects
            for (Employee e: staff)
                System.out.println("name=" + e.getName() + ", salary=" + e.getSalary());
        }
    }
    

    inheritance/Employee.java

    package inheritance;
    
    import java.time.*;
    public class Employee {
        private String name;
        private double salary;
        public Employee(String name, double salary, LocalDate hireDay) {
            this.name = name;
            this.salary = salary;
            this.hireDay = hireDay;
        }
        private LocalDate hireDay;
    
        public Employee(String name, double salary, int year, int month, int day)
        {
            this.name = name;
            this.salary = salary;
            hireDay = LocalDate.of(year, month, day);
        }
        public void setSalary(double salary) {
            this.salary = salary;
        }
        public String getName()
        {
            return name;
        }
    
        public double getSalary()
        {
            return salary;
        }
        public LocalDate getHireDay()
        {
            return hireDay;
        }
        public void raiseSalary(double byPercent)
        {
            double raise = salary * byPercent / 100;
            salary  += raise;
        }
    }
    

    inheritance/Manager.java

    package inheritance;
    
    public class Manager extends Employee
    {
        private double bonus;
        /**
         * @param name the employee's name
         * @param salary the salary
         * @param year the hire year
         * @param month the hire month
         * @param day the hire day
         */
        public Manager(String name, double salary, int year, int month, int day)
        {
            super(name, salary, year, month, day);
            bonus = 0;
        }
        public double getSalary()
        {
            double baseSalary = super.getSalary();
            return baseSalary + bonus;
        }
        public void setBonus(double b)
        {
            bonus = b;
        }
        
        
    }
    

    继承层次

    由一个公共超类派生出的所有类的集合称为** 继承层次(inheritance hierarchy)**, 某个子类指向其祖先的路径称为继承链(inheritance chain)

    多态

    “is-a”规则的另一种表述是替换原则(substitution principle) 指出程序中出现超类对象的任何地方都可以用子类方法替换。

    Employee e;
    e = new Employee(...);	//OK
    e = new Manager(...);			//OK
    

    在java中, 对象变量是多态的(polymorphic.)

    方法调用

    调用过程如下

    1. 编译器查看对象的声明类型和方法名
    2. 编译器确定方法调用中提供的参数类型, 这个过程称为重载解析(overloading resolution)
    3. 对于private方法, static方法 , final方法, 编译器将进行静态绑定(static binding), 如果调用的方法依赖于隐式参数的实际类型, 则必须在运行时使用动态绑定
    4. 程序运行时且采用动态绑定方法时, 虚拟机必须调用与x所引用对象的实际类型对应的方法, 虚拟机会为每个类计算一个方法表(method table)

    tips: 在覆盖一个方法时, 子类方法不能低于 超类方法的** 可见性**

    阻止继承: final类和方法

    如下, 可阻止派生Executive类的子类

    public final class Executive extends Manager
    {
    	...
    }
    

    同样可用来类中的某个特定方法, 使子类不能覆盖

    public class Employee
    {
    	...
    	public final String getName()
    	{
    		return name;
    	}
    }
    

    强制类型转换

    java中每个对象变量都有一个类型
    如果试图在继承链上进行向下的强制类型转换

    Manager boss = (Manager) staff[1];
    

    会产生ClassCastException的异常, 可以使用instanceof操作符进行转换

    if (staff[1] instanceof Manager)
    {
    	boss = (Manager) staff[1];
    }
    

    将超类强制转换为子类之前, 应该使用instanceof进行检查。
    只有在使用Manager中特有的方法时才进行强制类型转换

    抽象类

    继承层次位于上层的类更具有一般性
    使用abstract关键字可以完全不需要去实现该方法, 使其返回默认值

    public abstract class Person
    {
    	...
    	public abstract String getDescription();
    }
    

    这种类称为抽象类
    抽象类不能实例化

    public class Student extends Person
    {
    	private String major;
    	public Student (String name, String major)
    	{
    		super(name);
    		this.major = major;
    	}
    	public String getDescription()
    	{
    		return "a student majoring in " + major;
    	}
    	
    } 
    

    abstractClasses/PersonTest.java

    
    package abstractClasses;
    
    /**
     * This program demonstrates abstract classes.
     * @author Cay Horstmann
     */
    public class PersonTest
    {
        public static void main(String[] args)
        {
            var people = new Person[2];
            //fill the people array with Student and Employee objects
            people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
            people[1] = new Student("Maria Morris", "computer science");
    
            //print out names and descriptions of all Person objects
            for (Person p : people)
                System.out.println(p.getName() + ", " + p.getDescription());
        }
    }
    

    abstractClasses/Person.java

    package abstractClasses;
    
    public abstract class Person 
    {
        public abstract String getDescription();
        private String name;
        public Person(String name)
        {
            this.name = name;
        }
    
        public String getName()
        {
            return name;
        }
    }
    

    abstractClasses/Employee.java

    package abstractClasses;
    
    import java.time.*;
    public class Employee extends Person{
        private double salary;
        private LocalDate hireDay;
        
    
        public Employee(String name, double salary, int year, int month, int day)
        {
            super(name);
            this.salary = salary;
            hireDay = LocalDate.of(year, month, day);
        }
    
        public double getSalary()
        {
            return salary;
        }
        public LocalDate getHireDay()
        {
            return hireDay;
        }
        public String getDescription()
        {
            return String.format("an employee with a salary of %.2f", salary);
        }
        public void raiseSalary(double byPercent)
        {
            double raise = salary * byPercent / 100;
            salary  += raise;
        }
    }
    

    abstractClasses/Student.java

    package abstractClasses;
    
    public class Student extends Person
    {
        private String major;
    
        /**
         * @param name the student's name
         * @param major the student's major
         */
        public Student(String name, String major)
        {
            //pass name to superclass constructor
            super(name);
            this.major = major;
            
        }
        public String getDescription()
        {
            return "a student majoring in " + major;
        }
    
    }
    

    受访问保护

    若希望限制超类中某个方法 只允许子类访问, 或访问某个字段, 使用关键字protected
    java中保护字段只能由同一个包的类访问

    Object: 所有类的超类

    java中每个类都扩展了超类

    Object类型变量

    可以使用Object类型的变量引用任何类型的变量

    Object obj = new Employee("Harry Hacker", 35000 );
    Employee e = (Employee) obj;
    

    java中只有基本类型不是对象

    equals方法

    Object类中的equals方法将确定两个对象引用是否相等

    public class employee
    {
    	...
    	public boolean equals (Object otherObject)
    	{
    		//a quick test to see if the Objects and identical
    		if(this == otherObject) return true;
    
    		//must return false if the explicit parameter is null
    		if (otherObject == null) return false;
    
    		//if the classes don't match, they can not be equal
    		if (getClass() != otherObject.getclass())
    			return false;
    
    		//now we know otherObject is a non-null Employee
    		Employee other = (Employee) otherObject;
    		// test whether the fields have identical values
    		return name.equals(other.name)
    			&& salary == other.salary
    			&& hireDay.equals(other.hireDay);
    	}
    }
    

    getClass方法返回一个对象所属的类.

    相等测试和继承

    if (!(otherObject instanceof Employee))  return false
    

    允许 otherObject属于一个子类
    但这种方法不推荐
    java要求equals方法具有如下特质:

    1. 自反性
    2. 对称性
    3. 传递性
    4. 一致性
    5. 对非空引用x, x.equals(null)返回null

    如果子类可以有自己的相等性概念, 对称性需求将强制使用getClass检测
    如果由超类决定相等性概念, 那么可以使用instanceof来进行检测

    对于equals方法的建议 :

    1. 显式参数命名为otherObject, 稍后将其强制转换为另一个名为other的方法
    2. 检测this和otherObject是否相等
    3. 检测otherObject是否为null, 若null返回false
    4. 比较this与otherObject的类, 如果equals的语义可以在子类中改变, 使用getClass检测; 如果所有子类都有相同的相等性语义, 使用instanceof检测
    5. 将otherObect强制转换为相应类类型的变量
    6. 根据相等性概念进行字段比较; 如果在子类中重新定义equals, 就要在其中包含一个super.equals(other)调用

    equals方法必须覆盖Object的equals方法

    API

    java.util.Arrays
    static boolean equals​(Type[] a, int aFromIndex, int aToIndex, Type[] b, int bFromIndex, int bToIndex)
    Returns true if the two specified arrays of booleans are equal to one another.
    the Type coule be boolean, short, int, long, byte, char, float, double, Object
    FromIndex and ToIndex are optional
    java.util.Objects
    static boolean equals​(Object a, Object b)
    Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned. Otherwise, if the first argument is not null, equality is determined by calling the equals method of the first argument with the second argument of this method. Otherwise, false is returned.

    hashcode方法

    散列码(hash code)是由对象导出的一个整型值。
    String类使用如下算法计算hash code:

    int hash = 0;
    for (int i = 0; i < length(); i++)
    	hash = 31 * hash + charAt(i);
    

    hashCode方法定义在Object类中, 其值由对象的存储地址得出

    public class Employee
    {
    	public int hashCode()
    	{
    		return 7 * name.hashCode()
    			+ 11 * new Double(salary).hashCode()
    			+ 13 * hireDay.hashCode();
    	}
    	...
    }
    

    可以使用null安全的Objects.hashCode, 使用静态方法Double.hashCode来避免创建Double对象

    public int hashCode()
    {
    	return 7 * Objects.hashCode(name)
    		+ 11 * Double.hashCode(salary)
    		+ 13 * Objects.hashCode(hireDay);
    }
    

    需要组合多个散列值时, 可以使用Objects.hash并提供所有参数, 这个方法可以做到自动计算并组合

    public int hashCode()
    {
    	return Objects.hash(name, salary, hireDay);
    }
    

    API

    java.lang.Object
    int hashCode()
    Returns a hash code value for the object.
    java.util.Objects
    static int hash​(Object… values)
    Generates a hash code for a sequence of input values.
    static int hashCode​(Object o)
    Returns the hash code of a non-null argument and 0 for a null argument.
    java.lang.(Integer | Long | Short | Byte | Double | Float | Chatacter | Boolean)
    static int hashCode​(Type value)
    Returns a hash code for an int value; compatible with Integer.hashCode().
    java.util.Arrays
    static int hashCode​(Type[] a)
    Returns a hash code based on the contents of the specified array.
    The Type could be object, int, long, short, char, byte, boolean, float, double

    toString方法

    toString方法返回表示对象值的一个字符串

    public String toString()
    {
    	return "Employee[name=]" + name
    		+  ", salary=" + salary
    		+ ", hireDay=" + hireDay
    		+ "]";
    }
    

    可以通过getClass().getName()获得类名的字符串

    public String toString()
    {
    	return getClass().getName()
    	+ "[name=" + name
    	+ "salary=" + salary
    	+ "hireDay=" + hireDay
    	+ "]";
    }
    

    这样toString方法同样子类可以调用

    public class Manager extends Employee
    {
     	...
     	public String toString()
     	{
     		return super.toString()
     			+ "[bonus=" + bonus
     			+ "]";
     	}
    }
    

    如果x是一个任意对象

    System.out.println(x);
    

    println方法就会简单调用toString方法
    Object类定义的toString方法返回对象的类名和散列码

    System.out.println(System.out);
    

    equals/EqualsTest.java

    package equals;
    
    
    /**
     * This program demonstrates the equals method.
     * @author Cay Horstmann
     */
    public class EqualsTest 
    {
        public static void main(String[] args)
        {
            var alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
            var alice2 = alice1;
            var alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
            var bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
    
            System.out.println("alice1 == alice2: " + (alice1 == alice2));
            System.out.println("alice1 == alice3: " + (alice1 == alice3));
            System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
            System.out.println("alice1.equals(bob): " + alice1.equals(bob));
            System.out.println("bob.toString(): " + bob);
    
            var carl  = new Manager("Carl Cracker", 80000, 1987, 12, 15);
            var boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
            boss.setBonus(5000);
    
            System.out.println("boss.toString(): " + boss);
            System.out.println("carl.equals(boss): " + carl.equals(boss));
            System.out.println("alice1.hashCode(): " + alice1.hashCode());
            System.out.println("alice3.hashCode(): " + alice3.hashCode());
            System.out.println("bob.hashCode(): " + bob.hashCode());
            System.out.println("carl.hashCode(): " + carl.hashCode());
        }
    }
    

    equals/Employee.java

    package equals;
    
    import java.time.*;
    import java.util.Objects;
    
    
    public class Employee {
        private String name;
        private double salary;
        private LocalDate hireDay;
    
        public Employee(String name, double salary, LocalDate hireDay) {
            this.name = name;
            this.salary = salary;
            this.hireDay = hireDay;
        }
    
        public Employee(String name, double salary, int year, int month, int day)
        {
            this.name = name;
            this.salary = salary;
            hireDay = LocalDate.of(year, month, day);
        }
        public void setSalary(double salary) {
            this.salary = salary;
        }
        public String getName()
        {
            return name;
        }
    
        public double getSalary()
        {
            return salary;
        }
        public LocalDate getHireDay()
        {
            return hireDay;
        }
        public void raiseSalary(double byPercent)
        {
            double raise = salary * byPercent / 100;
            salary  += raise;
        }
    
        public boolean equals(Object otherObject)
        {
            //a quick test to see if the Objeccts are identical
            if(this == otherObject) return true;
    
            //must return false if the explicit parameter is null
            if(otherObject == null) return false;
            // if the classes do not match, they can not be equal
            if(getClass() != otherObject.getClass()) return false;
            
            //now we know otherObject is a non-null Employee
            var other = (Employee) otherObject;
            //test whether the fields have identical values
            return Objects.equals(name, other.name)
                && salary == other.salary && Objects.equals(hireDay, other.hireDay);
        }
    
        public int hashCode()
        {
            return Objects.hash(name, salary, hireDay);
        }
        public String toString()
        {
            return getClass().getName() + "[name=" + name + ", salary=" + salary + ", hireDay="
                + hireDay + "]"; 
        }
    }
    

    equals/Manager.java

    package equals;
    
    public class Manager extends Employee
    {
        private double bonus;
        /**
         * @param name the employee's name
         * @param salary the salary
         * @param year the hire year
         * @param month the hire month
         * @param day the hire day
         */
        public Manager(String name, double salary, int year, int month, int day)
        {
            super(name, salary, year, month, day);
            bonus = 0;
        }
        public double getSalary()
        {
            double baseSalary = super.getSalary();
            return baseSalary + bonus;
        }
        public void setBonus(double b)
        {
            bonus = b;
        }
        
    
        public boolean equals(Object otherObject)
        {
            if (!super.equals(otherObject)) return false;
            var other = (Manager) otherObject;
            //super.equals checked that this and other belong to the same class
            return bonus == other.bonus;
        }
    
        public int hashCode()
        {
            return java.util.Objects.hash(super.hashCode(), bonus);
        }
    
        public String toString()
        {
            return super.toString() + "[bonus=" + bonus + "]";
        }
        
    }
    

    泛型数组列表

    ArrayList类类似于数组, 但可以自动调整数组容量
    ArrayList是一个有** 参数类型(type parameter)** 的** 泛型类(generic class) **用一堆尖括号<>将类名追加到ArrayList之后来指定数组列表保存的元素对象类型

    声明数组列表

    ArrayList<Employee> staff = new ArrayList<Employee>();
    var staff = new ArrayList<Employee>();
    ArrayList<Employee> staff = new ArrayList<>();
    

    这称为"菱形"语法
    使用var进行声明时菱形语法不可用
    使用add方法进行元素添加

    staff.add(new Employee("Harry Hacker", ... ));
    staff.add(new Employee("Tony Tester", ....));
    

    如果可能存储单位已知, 可以在填充数组列表之前调用ensureCapacity方法:

    staff.ensureCapacity(100);
    
    ArrayList<Employee> staff = new ArrayList<>(100);
    

    size方法返回数组列表中包含的实际元素个数

    staff.size()
    

    等价于数组的a.length.
    确定数组列表的大小将保持恒定, 调用trimToSize方法

    API

    java.util.ArrayList
    ArrayList()
    Constructs an empty list with an initial capacity of ten.
    ArrayList​(int initialCapacity)
    Constructs an empty list with the specified initial capacity.
    void add​(int index, E element)
    Inserts the specified element at the specified position in this list.
    boolean add​(E e)
    Appends the specified element to the end of this list.
    int size()
    Returns the number of elements in this list.
    void ensureCapacity​(int minCapacity)
    Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
    void trimToSize()
    Trims the capacity of this ArrayList instance to be the list’s current size.

    访问数组列表元素

    不能使用数组下标法进行数组列表的访问与元素设置

    staff.set(i, harry);
    Employee e = staff.get(i);
    

    以下技巧既可以灵活扩展数组, 又可以方便的访问数组元素

    var list = new ArrayList<x>();
    while (...)
    {
    	x= ...;
    	list.add(x);
    }
    

    随后使用toArray方法拷贝进一个数组

    var a = new X[list.size()];
    list.toArray(a);
    

    使用add方法在数组列表中间插入元素

    int n = staff.size() / 2;
    staff.add(n, e);
    

    arrayList/ArrayListTest.java

    package arraylist;
    
    import java.util.*;
    /**
     * This program demonstrates the ArrayList class.
     * @author Cay Horstmann
     */
    
    public class ArrayListTest 
    {
        public static void main(String[] args)
        {
            //fill the staff array list with three Employee objects
            var staff = new ArrayList<Employee>();
            
            staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
            staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
            staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
    
            //raise everyone's salary by 5%
            for (Employee e: staff)
                e.raiseSalary(5);
    
            //print out information about all Employee objects
            for (Employee e: staff)
                System.out.println("name=" + e.getName() + ", salary=" + e.getSalary() + " ,hireDay=" + e.getHireDay());
        }
        
    }
    

    API

    java.util.ArrayList
    E set​(int index, E element)
    Replaces the element at the specified position in this list with the specified element.
    E get​(int index)
    Returns the element at the specified position in this list.
    void add​(int index, E element)
    Inserts the specified element at the specified position in this list.
    E remove​(int index)
    Removes the element at the specified position in this list.

    类型化与原始数组列表的兼容性

    假设有下面这个遗留下来的类

    public class EmployeeDB
    {
    	public void update(ArrayList list){...}
    	public ArrayList find (String query){...}
    }
    

    可以将一个类型化数组传递给update方法不需要进行强制转化

    ArrayList<Employee> staff = ...;
    employeeDB.update(staff);
    

    反之将一个原始ArrayList赋给一个类型化ArrayList会得到一个警告

    ArrayList<Employee> result = employeeDB.find(query);		//yields warning
    

    使用强制转换将会得到另一个警告消息, 指出类型转换有误。
    在于这些遗留代码交互后确定警告不太严重后, 可以用@SuppressWarnings(“unchecked”)注解来标记接受强制类型转换的变量

    @SuppressWarnings("unchecked") ArrayList<Employee> result
    	= (ArrayList<Employee>) employeeDB.find(query); 		//yield another warning
    

    对象包装器与自动装箱

    所有基本类型都有一个与之对应的类
    Integer, Long, Float, Double, Short, Byte, Chatacter和Boolean(前六个类诞生于超类Number)
    若要定义一个整型数组列表, 类型参数不允许是基本类型

    var list = new ArrayList<Integer>();
    
    list.add(3);
    

    将自动变换为

    list.add(Integer.valueOf(3));
    

    这种变换称为自动装箱(autoboxing)
    将一个Integer对象赋给一个int值时, 也将会自动的拆箱
    其同样适用于算术表达式
    但其与基本类型在同一性有区别, == 可以应用于包装器对象, 但检测的是是否有相同的内存位置。
    在比较两个包装器对象时还是使用equals方法比较好
    如果在一个条件表达式中混用integer和Double, Integer值就会拆箱, 提升为Double, 再装箱为Integer:

       Integer n = 1;
          Double x = 2.0;
          out.println(true? n : x);
    

    装箱和拆箱为编译器执行的工作, 而非虚拟机
    要想将字符串转换为整型, 可以使用parseInt(s);

    int x = Integer.parseInt(s);
    

    API

    java.lang.Integer
    int intValue()
    Returns the value of this Integer as an int.
    static String toString​(int i)
    Returns a String object representing the specified integer.
    static String toString​(int i, int radix)
    Returns a string representation of the first argument in the radix specified by the second argument.
    static int parseInt​(String s)
    Parses the string argument as a signed decimal integer.
    static int parseInt​(String s, int radix)
    Parses the string argument as a signed integer in the radix specified by the second argument.
    static Integer valueOf​(int i)
    Returns an Integer instance representing the specified int value.
    static Integer valueOf​(String s)
    Returns an Integer object holding the value of the specified String.
    static Integer valueOf​(String s, int radix)
    Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument.
    java.text.NumberFormat
    Number parse​(String source)
    Parses text from the beginning of the given string to produce a number

    参数数量可变的方法

    有时这些方法称为变参(varargs)方法。
    printf方法定义如下:

    public class PrintStream
    {
    	public PrintStream printf(String fmt, Object... args){return format(fmt, args);}
    }
    

    省略号…表明这个方法可以接受任意数量参数。
    Object…参数类型与Object[]完全一致

    System.out.printf("%d %s", new Object[] {new Integer(n), "widgets"});
    

    如下函数可以计算若干个数值的最大值

    public static double max(double... values)
    {
    	double largest = Double.NEGATIVE_INFINITY;
    	for (double v: values) if(v > largest)  largest = v;
    	return largest;
    }
    

    枚举类

    public enum Size {SMALL, MEDIUM, LARGE, EXTRA_LARGE}
    

    实际上这个声明定义的类型是一个类, 在比较两个枚举类型的值时, 直接使用==即可
    可以为枚举类型增加构造器, 方法和字段

    public enum Size
    {
    	SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
    	private String abbreviation;
    	private Size(String abbreviation) {this.abbreviation = abbreviation; }
    	public String getAbbreviation() {return abbreviation; }
    }
    

    toString方法返回枚举类型的枚举常量名,其逆方法为静态方法valueOf。
    枚举类型的静态values方法将返回一个包含全部枚举值的数组

    Size[] values = Size.values();
    

    ordinal方法返回enum声明中枚举常量的位置, 从零开始计数

    Size.MEDIUM.ordinal()
    

    返回1
    enums/EnumTest.java

    package enums;
    
    import java.util.*;
    
    
    /**
     * This program demonstrates enumerated types.
     * @author Cay Horstmann
     */
    public class EnumTest 
    {
        
        public static void main(String[] args)
        {
            var in = new Scanner(System.in);
            System.out.print("Enter a size:(SMALL, MEDIUM, LARGE, EXTRA_LARGE)");
            String input = in.next().toUpperCase();
            Size size = Enum.valueOf(Size.class, input);
            System.out.println("abbreviation=" + size.getAbbreviation());
            if (size == Size.EXTRA_LARGE)
            {
                System.out.println("Good job--you paid attention to the _.");
            }
            
        }
        
    }
    enum Size
    {
        SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
    
        private Size(String abbreviation) {this.abbreviation = abbreviation;}
        public String getAbbreviation() {return abbreviation;}
    
        private String abbreviation;
    }
    

    API

    java.lang.Enum
    static <T extends Enum< T >>T valueOf​(Class< T > enumClass, String name)
    Returns the enum constant of the specified enum class with the specified name.
    String toString()
    Returns the name of this enum constant, as contained in the declaration.
    int ordinal()
    Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
    int compareTo​(E o)
    Compares this enum with the specified object for order.

    反射

    反射库(reflection library)提供了一个工具集用来编写可以动态操纵java代码的程序, 使用反射可完成很多需要动态查询类能力的开发工具。
    能够分析类能力的程序称之为反射(reflective)
    反射机制可以

    1. 运行时分析类的能力
    2. 运行时检查对象
    3. 实现泛型数组操作代码
    4. 利用method对象, 类似于函数指针

    Class类

    程序运行期间java始终为所有对象维护一个运行时类型标识, 该信息跟踪每个对象所属的类
    可以使用Class类访问这些信息。

    Employee e;
    ...
    Class cl = e.getClass();
    

    Class对象会描述一个特定类的属性, 最常用的Class方法通常是getName。
    如果类在一个包里, 包的名字也会是类名的一部分

    var generator = new Random();
    Class cl = generator.getClass();
    String name = cl.getName();		name is set to "java.util.Random'
    

    forName静态方法可以获取类名对应的Class对象

    String className = "java.util.Random";
    Class cl = Class.forName(className);
    

    如果className不是一个类名或接口名, forName方法会抛出一个检查型异常(checked exception), 使用该方法时应该提供一个** 异常处理器(exception handler)**

    如果T是任意的java类型(或void), T.class将代表匹配的类对象

    Class cl1 = Random.class;
    Class cl2 = int.class;
    Class cl3 = Double[].class
    

    可以利用==实现两个类对象的比较, 与条件e instanceof Employee不同, 若e为子类的实例, 仍然不会通过

    if (e.getClass() == Employee.class)...
    

    getConstructor方法将得到一个Constructor类型对象, 随后可以使用newInstance方法创造一个实例

    var className = "java.util.Random";
    Class cl = Class.forName(className);
    Object obj = cl.getConstructor().newInstance();
    

    API

    java.lang.Class
    static Class<?> forName​(String className)
    Returns the Class object associated with the class or interface with the given string name.
    Constructor getConstructor​(Class<?>… parameterTypes)
    Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
    Constructor<?>[] getConstructors()
    Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
    java.lang.reflect.Constructor
    T newInstance​(Object… initargs)
    Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters.
    java.lang.Throwable
    void printStackTrace()
    Prints this throwable and its backtrace to the standard error stream.
    void printStackTrace​(PrintStream s)
    Prints this throwable and its backtrace to the specified print stream.

    声明异常

    抛出异常时可以提供一个处理器(handler) 捕获该异常并处理
    异常有两种类型:** 非检查型(unchecked)检查型(checked)** 异常
    通常越界错误或访问null引用, 都属于非检查型异常, 这类异常应该尽力避免, 而不是去编写异常处理器
    类似Class.forName方法, 很多方法都会抛出一个检查型异常

    增加throws子句

    public static void doSomethingWithClass(String name)
    	throws ReflectiveOperationException
    	{
    		Class cl = class.forName(name);		//might throw exception
    	}
    

    资源

    Class类提供了一个服务可以查找资源文件

    1. 获得拥有资源的的类的class对象, 例如ResourceTest.class
    2. 有些方法接受描述资源位置的URL,, 则要调用
    URL url = cl.getResource("about.gif");
    
    1. 否则使用getResourceAsStream方法得到一个输入流来读取文件中的数据

    文件的自动装载是利用资源加载特性完成, 没有标准方法来解释资源文件内容
    resource/ResourceTest.java

    package resources;
    
    import java.io.*;
    import java.net.*;
    import java.nio.charset.*;
    import javax.swing.*;
    
    /**
     * @author Cat Horstmann
     */
    
    
    public class ResourceTest 
    {
        public static void main(String[] args) throws IOException
        {
            Class cl = ResourceTest.class;
            URL aboutURL = cl.getResource("about.gif");
            var icon = new ImageIcon(aboutURL);
    
            InputStream stream = cl.getResourceAsStream("data/about.txt");
            var about = new String(stream.readAllBytes(), "UTF-8");
    
            InputStream stream2 = cl.getResourceAsStream("title.txt");
            var title = new String(stream2.readAllBytes(), StandardCharsets.UTF_8).trim();
    
            JOptionPane.showMessageDialog(null, about, title, JOptionPane.INFORMATION_MESSAGE, icon);
        }
    }
    

    API

    java.lang.Class
    static Class<?> forName​(String className)
    Returns the Class object associated with the class or interface with the given string name.
    URL getResource​(String name)
    Finds a resource with a given name.
    InputStream getResourceAsStream​(String name)
    Finds a resource with a given name.

    利用反射分析类的能力

    java.lang.reflect包中有三个类Field, Method和Constructor分别描述类的字段, 方法和构造器
    这三个类都有一个叫做getName的方法, 用来返回字段, 方法或构造器的名称。

    展开全文
  • Java 核型技术第十一 卷一和卷二的随书源代码 Prentice.Hall.Core.Java.Volume.I.Fundamentals.11th.Edition source code Prentice.Hall.Core.Java.Volume.II.Advanced.Features.11th.Edition source code
  • 核心java java核心技术第11版
  • JAVA核心技术第11版卷1,2》 Java核心技术与Thinking in Java(Java编程思想)齐名的 Core Java。2018年9月才出版的英文原版,包括了Java9,Java10,Java11的新特性,中文的翻译版还没有出,估计还要很久,多看看...

    《JAVA核心技术第11版卷1,2》 Java核心技术与Thinking in Java(Java编程思想)齐名的 Core Java。2018年9月才出版的英文原版,包括了Java9,Java10,Java11的新特性,中文的翻译版还没有出,估计还要很久,多看看英文文档对自己也是很有帮助的。书中囊括了Java的全部基础知识,提供了大量完整且具有实际意义的应用示例,详细介绍了Java语言基础、面向对象编程、反射与代理、接口与内部类、事件监听器模型、使用Swing GUI工具进行图形用户界面程序设计、打包应用程序、异常处理、登录与调试、泛型编程、集合框架、多线程、并发等内容。本书赢得了全球程序员的广泛赞誉,即使是最晦涩的概念,在Bruce Eckel的文字亲和力和小而直接的编程示例面前也会化解于无形。从Java的基础语法到最高级特性(深入的面向对象概念、多线程、自动项目构建、单元测试和调试等),本书都能逐步指导你轻松掌握。
    《JAVA编程思想第四版中文版》 从本书获得的各项大奖以及来自世界各地的读者评论中,不难看出这是一本经典之作。本书的作者拥有多年教学经验,对C、C++以及Java语言都有独到、深入的见解,以通俗易懂及小而直接的示例解释了一个个晦涩抽象的概念。本书共22章,包括操作符、控制执行流程、访问权限控制、复用类、多态、接口、通过异常处理错误、字符串、泛型、数组、容器深入研究、Java I/O系统、枚举类型、并发以及图形化用户界面等内容。这些丰富的内容,包含了Java语言基础语法以及高级特性,适合各个层次的Java程序员阅读,同时也是高等院校讲授…
    提取码:rnal

    展开全文
  • Java 核心技术 卷Ⅰ 基础知识 第11版 英文版 Core Java Volume I–Fundamentals Eleventh Edition Cay S. Horstmann
  • Java核心技术 卷1 原书第11版(最新版),卷2目前还没有,后续再更新上传
  • Java核心技术卷一基础知识第10配套代码
  • Java核心技术第11版)卷1 勘误1

    千次阅读 2019-12-29 11:25:25
    在书的第50页: boolean blank() 应改为 boolean isBlank()

    在书的第50页:

    boolean blank()

    应改为

    boolean isBlank()

     

    展开全文
  • 11th Edition Volume 1 (Java SE 9 - 11) Page 54 Change “Except, of course, when n is negative.” to “Except, of course, when n is odd and negative.” Page 69 Change the method names empty and blank ...

    11th Edition Volume 1 (Java SE 9 - 11)
    Page 54
    Change “Except, of course, when n is negative.” to “Except, of course, when n is odd and negative.”
    Page 69
    Change the method names empty and blank to isEmpty and isBlank.
    Page 69
    In the API note for the startsWith/endsWith methods, change “returns true if the string starts or ends with suffix.” to “returns true if the string starts with prefix or ends with suffix.”
    Page 628 preferences/ImageViewer.java
    Change line 60 from
    node.put("image", image);
    to
    if (image != null) node.put("image", image);

    来源:http://horstmann.com/corejava/bugs.html#CJ11V1

    展开全文
  • 中文 来源:... ... 英文 Prentice.Hall.Core.Java.Volume.I.Fundamentals.11th.Edition.pdf 下载地址:https://github.com/yizutianya/corejavahttps://gitee.com/tuziang/corejava ...
  • Core Java Volume I Fundamentals 11th Edition Core Java, Volume II--Advanced Features, 11th Edition
  • 新书推荐《Java核心技术卷Ⅰ:基础知识(原书第11版)》长按二维码了解及购买全新第11版!针对Java SE9、10、11全面更新!Java领域极具影响力和价值的著作之一,与《Java...
  • 新书推荐《Java核心技术 卷II 高级特性(原书第11版)》长按二维码了解及购买全新第11版!针对Java SE9、10、11全面更新!Java领域极具影响力和价值的著作之一,与《Ja...
  • 第三章 Java的基本程序设计结构(上)3.1 一个简单的java应用程序3.1.1 注意点3.2 注释3.3 数据类型3.3.1 整型3.3.2 浮点类型3.3.3 char类型3.3.4 Unicode 和 char 类型3.3.5 boolean 类型3.4 变量与常量3.4.1 声明...

空空如也

空空如也

1 2 3
收藏数 54
精华内容 21
关键字:

java核心技术第11版

java 订阅