`

core-java学习【一】

    博客分类:
  • Java
阅读更多
import java.util.*;

public class Employee 
{
    //构造器,-------------------------------------------------注意参数的命名规则
    //默认构造器
    public Employee()
    {   
        
    }
    public Employee(String firstName , String lastName , double salary , int year, int month, int day)
    {
        this.firstName = firstName ;//不要在构造器中定义与实例域重名的局部变量,如:String firstName = f ;
        this.lastName = lastName ;
        this.salary = salary ;
        GregorianCalendar calendar = new GregorianCalendar(year,month - 1,day);
        // GregorianCalendar uses 0 for January
        this.hireDay = calendar.getTime() ;
    }
    
    public Employee(String firstName , String lastName , double salary)
    {
        this.firstName = firstName ;
        this.lastName = lastName ;
        this.salary = salary ;
    }
    
    public Employee(double salary)
    {
        this.salary = salary ;
    }
    /*public Employee(double salary)
    {
        //calls Employee(String, String, double)
        this() ;
        //nextId++ ;
    }*/
    
    // 定义方法
    public int getId()
    {
        return id ;
    }
    
    public String getName()
    {
        return firstName+" "+lastName ;
    }
    
    public double getSalary()
    {
        return salary ;
    }
    
    //----------------------------------------------若需返回一个可变数据域的拷贝,应该使用克隆,以免破坏封装性
    public Date getHireDay()
    {
        return (Date)hireDay.clone() ;
    }
    
    //----------------------------------------------关键字this表示隐式参数
    public void raiseSalary(double byPercent)
    {
        double raise = this.salary * byPercent /100 ;
        this.salary += raise ;
    }
    
    // 定义 equals 方法=======================================================================
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are 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't 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 idential values
        return firstName.equals(other.firstName)
        && lastName.equals(other.lastName)
        && salary == other.salary
        && hireDay.equals(other.hireDay) ;
    }
    
    // 定义hashCode方法======================================================================
    public int hashCode()
    {
        return 7 * firstName.hashCode()
        + 11 * lastName.hashCode()
        + 13 * new Double(salary).hashCode()
        + 17 * hireDay.hashCode() ;
    }
    
    // 定义 toString 方法=======================================================================
    public String toString()
    {
        return getClass().getName()
        + "[ firstName= " + firstName
        + " , lastName= " + lastName
        + " , salary= " + salary
        + " , hireDay= " + hireDay
        +" ] " ;
    }
      
    //定义 域
    private static int nextId ;
    
    private int id ;
    private String firstName = " ";//实例域初始化
    private String lastName = " ";//实例域初始化
    /*
    private final String firstName ;//String类是一个不可变的类,声明为final类型
    private final String lastName ;//表示对象在构建之后不会再被修饰,即没有setName方法
    */
    private double salary ;
    private Date hireDay ;
    
    //静态初始化块
    static
    {
        Random generator = new Random() ;
        //set nextId to a random number between 0 and 9999
        nextId = generator.nextInt(10000) ;
    }
    
    //对象初始化块
    {
        id = nextId ;
        nextId++ ;
    }
}

 

 

public class Manager extends Employee 
{
    // 定义构造器,通过super 调用超类的构造器
    public Manager(String firstName , String lastName , double salary , int year , int month , int day )
    {
        super(firstName , lastName , salary , year , month , day) ;
        bonus = 0 ;
    }
    
    // 定义子类的getSalary方法,覆盖超类中的getSalary方法
    public double getSalary() 
    {
        double baseSalary = super.getSalary() ;//通过super调用超类的getSalary方法
        return baseSalary + bonus ;
    }
    
    public void setBonus(double bonus)
    {
        this.bonus = bonus ;
    }
    
    // 定义子类Manager对象的equals方法,通过super调用超类的equals方法
    public boolean equals(Object otherObject)
    {
        if(!super.equals(otherObject))
            return false ;
        Manager other = (Manager) otherObject ;
        // super.equals checked that this and other belong to the same class
        return this.bonus == other.bonus ;
    }
    
    // 定义子类的hashCode方法
    public int hashCode()
    {
        return super.hashCode()
        + 19 * new Double(bonus).hashCode() ;
    }
    
    // 定义子类的toString方法
    public String toString()
    {
        return super.toString()
        + "[ bonus= " + bonus
        + " ]" ;
    }
    
    private double bonus ;
}

 

 

 

public class EqualsTest 
{
    public static void main(String[] args) 
    {
        Employee alices1 = new Employee("Alice", "Adams", 75000, 1987, 12, 15) ;
        Employee alices2 = alices1 ;
        Employee alices3 = new Employee("Alice", "Adams", 75000, 1987, 12, 15) ;
        Employee bob = new Employee("Bob", "Brandson", 50000, 1989, 10, 1) ;
        
        System.out.println("alices1 == alices2: " + (alices1 == alices2)) ;
        System.out.println("alices1 == alices3: " + (alices1 == alices3)) ;
        System.out.println("alices1.equals(alices3): " + alices1.equals(alices3)) ;
        System.out.println("alices1.equals(bob): " + alices1.equals(bob)) ;
        
        System.out.println("bob.toString(): " + bob) ;
        
        Manager carl = new Manager("Carl", "Cracker", 80000, 1987, 12, 15) ;
        Manager 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("alices1.hashCode(): " + alices1.hashCode()) ;
        System.out.println("alices3.hashCode(): " + alices3.hashCode()) ;
        System.out.println("bob.hashCode(): " + bob.hashCode()) ;
        System.out.println("carl.hashCode(): " + carl.hashCode()) ;
    }
}

 

 

public class EmployeeTest
{
    public static void main(String[] args)
    {
        //fill the staff array with three Employee objects
        Employee[] staff = new Employee[3];
        
        staff[0] = new Employee("Carl","Crack",75000,1987,12,15);
        staff[1] = new Employee("Harry","Hacker",50000,1989,10,1);
        staff[2] = new Employee("Tony","Tester",40000,1990,3,15);
        
        //raise everyone's salary by 5%
        for(Employee e : staff)
            e.raiseSalary(5);//使用for each 循环结构
        
        //print out information about all Employee objects
        for(Employee e : staff)
            System.out.println("name= " + e.getName()
                    +",salary= "+e.getSalary()
                    +",hireDay= "+e.getHireDay());
    }

}

 

 

public class ManagerTest
{
    public static void main(String[] args)
    {
        // constructor a Manager object 
        Manager boss = new Manager("Carl" , "Cracker" , 80000 , 1987 , 12 ,15) ;
        boss.setBonus(5000) ;
        
        Employee[] staff = new Employee[3] ;
        
        // fill the staff array with Manager and Employee objects
        
        staff[0] = boss ; //置换法则,将Manager类对象赋值给Employee类对象
        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()) ;//此处的变量e即引用了超类Employee的getSalary方法,又同时引用了子类Manager的getSalary方法,这种现象叫做多态。
        }

}

 

 

public class ParamTest 
{
    public static void main(String[] args) 
    {
        /*
               Test 1: Methods can't modify numeric parameters
                                    一个方法不能修改一个基本数据类型的参数(即数值型和布尔型值)
         */
        System.out.println("Testing tripleValue:");
        double percent = 10 ;
        System.out.println("Before: percent= "+percent);
        tripleValue(percent);
        System.out.println("After: percent= "+percent);
        
        /*
               Test 2: Methods can change the state of object parameters
                                    一个方法可以改变一个对象参数的状态
         */
        System.out.println("\nTesting tripleSalary: ");
        Employee harry = new Employee("Harry " , "Crack" , 5000);
        System.out.println("Before: salary= "+harry.getSalary());
        tripleSalary(harry);
        System.out.println("After: salary= "+harry.getSalary());
        
        /*
                 Test 3: Methods can't attach new objects to object parameters
                                       一个方法不能让对象参数引用一个新的对象
        */
        System.out.println("\nTesting swap: ");
        Employee a = new Employee("Eric" , "Zhang" , 70000);
        Employee b = new Employee("Huiyi" , "Chang" , 50000);
        System.out.println("Before: a= "+a.getName());
        System.out.println("Before: b= "+b.getName());
        swap(a,b);
        System.out.println("After: a= "+a.getName());
        System.out.println("After: b= "+b.getName());
    }
    
    //Test 1
    public static void tripleValue(double x) //does'nt work
    {
        x = 3 * x ;
        System.out.println("End of Method: x= "+x );
    }
    
    //Test 2
    public static void tripleSalary(Employee x) //works
    {
        x.raiseSalary(200);
        System.out.println("End of Methods: salary= "+x.getSalary());
    }
    
    //Test 3
    public static void swap(Employee x , Employee y) 
    {
        Employee temp = x ;
        x = y ;
        y = temp ;
        System.out.println("End of Methods: x = "+x.getName());
        System.out.println("End of Methods: y = "+y.getName());
    }
}

/*结果如下:
Testing tripleValue:--------------------------------------未发生改变
Before: percent= 10.0
End of Method: x= 30.0
After: percent= 10.0

Testing tripleSalary: ------------------------------------发生改变
Before: salary= 5000.0
End of Methods: salary= 15000.0
After: salary= 15000.0

Testing swap: --------------------------------------------a,b未发生改变,x,y发生改变
Before: a= Eric Zhang
Before: b= Huiyi Chang
End of Methods: x = Huiyi Chang
End of Methods: y = Eric Zhang
After: a= Eric Zhang
After: b= Huiyi Chang
 */

 

import java.util.*;

public class CalendarTest 
{
    public static void main(String[] args) 
    {
        //construct d as current date构造一个日历对象
        GregorianCalendar d = new GregorianCalendar();
        
        //2次调用get方法得到当时的日、月
        int today = d.get(Calendar.DAY_OF_MONTH);
        int month = d.get(Calendar.MONTH);
        
        // set d to start date of the month将d设置为这个月的第一天
        d.set(Calendar.DAY_OF_MONTH,1);
        
        //并且获得第一个月的第一天是星期几
        int weekday = d.get(Calendar.DAY_OF_WEEK);
        
        //print heading
        System.out.println("  Sun  Mon  Tue  Wed  Thu  Fri  Sat ");
        
        // indent first line of calendar
        for(int i = Calendar.SUNDAY; i < weekday; i++)
            System.out.print("         ");
        
        do
        {
            //print day
            int day = d.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%4d", day);
            
            //mark current day with *
            if(day == today)
                System.out.print("*");
            else
                System.out.print("  ");
            
            //start a new line after every Saturday
            if(weekday == Calendar.SATURDAY)
                System.out.println();
            
            //advanced d to the next day
            d.add(Calendar.DAY_OF_MONTH,1);
            weekday = d.get(Calendar.DAY_OF_WEEK);
        }
        while (d.get(Calendar.MONTH) == month);
        // the loop exits when d is day 1 of the the next month
        
        //print final end of line if necessary
        if (weekday != Calendar.SUNDAY)
            System.out.println();
    }
    
}

 

 

 

分享到:
评论
1 楼 csdn_zuoqiang 2010-07-18  
100以内的质数(素数):2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 (共25个)、
在计算hashCode的时候用得着

相关推荐

Global site tag (gtag.js) - Google Analytics