JAVA类与对象

  Employee类:

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 Cracker", 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);

      // print out information about all Employee objects
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
               + e.getHireDay());
   }
}

class Employee
{
   public Employee(String n, double s, int year, int month, int day)
   {
      name = n;
      salary = s;
      GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
      // GregorianCalendar uses 0 for January
      hireDay = calendar.getTime();
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public Date getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   private String name;
   private double salary;
   private Date hireDay;
}

  对象变量是一个引用

例如:Employee zhangsan = new Employee("zhangsan",2000,2009,2,1);

其中new Employee建立了一个对象,但是new操作符返回对该对象的引用,并赋值给zhangsan变量,所以zhangsan仅为对象的引用,

而在Employee zhangsan2 = zhangsan中,将zhangsan引用赋值给zhangsan2,此时zhangsan和zhangsan2都将引用同一个对象。

对象变量可以初始化为null,例如Employee zhangsan = null;

  在一个源文件中,只允许有一个公有类,但可以有任意数目的非公有类

例如EmployeeTest类即公有类,Employee 为非公有类

     注意不要编写返回引用可变对象的方法

     在函数getHireDay中,返回的是Date类对象的引用,这样会破坏封装性,例如下面的代码:

Employee harry = new harry("Harry",2000,1990,10,12);

Date date = harry.getHireDay();

double tenYearInMilliSeconds = 10 * 365 * 24 * 60 * 60 *1000;

d.setTime(d.getTime() - (long)tenYearInMilliSeconds);

    出错的原因很简单,就是因为d和harry.hireDay引用同一个Date对象,对d调用setTime方法,就可以任意修改雇员对象的私有状态,如果需要返回一个可变对象的引用,应该首先对它进行克隆,即建立一个对象副本,修改代码如下:

public Date getHireDay()
{
    return (Date) hireDay.clone();
}

    每个类成员方法都有一个隐式参数,即调用该方法的对象,关键字this表示隐式参数

    例如可以这样编写raiseSalary方法:

public void raiseSalary(double byPercent)
{
    double raise = this.salary * byPercent / 100;
    this.salary += raise;
}

    java的所有方法都需要在类内部定义,但并不是在类内部就代表内联方法,是否将某个方法设置为内联方法是java虚拟机的任务

 

posted @ 2013-11-16 23:28  王耀it  阅读(257)  评论(0编辑  收藏  举报