To study Java -- objects and classes (a)

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Prior to the adoption of methods of note taking, for "Java core technology" this book the first chapter was re review, feel the effect is very good, better than read a book review the effect brought about some of the details, many previously not very attention, but in some of their more familiar places, such as an array, cycle, when reviewing looks a bit impatient, do not seriously read a book, this is also the need to continue to progress.

When I just started learning Java, for object oriented, some knowledge is always do not understand, but this piece of knowledge is really very important, don't understand to the increase in Java is also very helpful, so I hope to be able to in this review to continue to improve their understanding of the.

1 object oriented programming

Object oriented programming, referred to as OOP, is the design specification of the current mainstream, have replaced the “ structured ” process design and development technology.

Object oriented programming is composed of objects, each object contains a specific function part of the user to open and the hidden part of implementation. Program in many objects from the standard library, as well as some custom. Fundamentally speaking, as long as the object is able to meet the requirements, need not care about its function realization process.

Traditional structured programming to solve the problem through the design process of some columns. These processes once decided, to start thinking about the ways of storing data. This is why the data structure course has been very important, but I could not understand, because when I started learning, came in contact with the object oriented programming method, rather than the traditional structure. A previous program first consideration is the algorithm, namely how to manipulate data, second is the data structure, namely, how to organize data. And now the first data is, and then consider how to manipulate the data. And object oriented for large projects, is relatively simple.

1.1 class

Class is constructed object templates or blueprint. The object is constructed the process called to create an instance of the class . The class is equivalent to the drawings, and example corresponds to a specific product.

Package , sometimes referred to as data hiding, is an important concept and object related. From the formal point of view, the package is combining data and behavior in a package, and the user of the object to hide the implementation mode data. The data in the object as an instance of domain , manipulate the data process called method. For each specific class instance has a specific set of examples of domain values. The current state, the set of values is the object matter when, can send a message to the object, its state may change.

The package is the key to absolutely can not let the methods in a class directly access instance fields of other classes. Communicate only through the object program method and object. Given the characteristics of the object encapsulation of the black box, this is the key to improve the reusability and reliability of .

Another principle is: OOP classes can be established by extended another class. Java all classes from the Object class, this class is all kind of father (because in my opinion, everything is an object, so come from Object). For an existing class extension, the new class of this extension of extended all the attributes and methods of classes with. In the new class, only need to provide some methods and data domain only applies to new classes can be. This process is called inheritance.

1.2 object

The three main characteristics of the object: object behavior, the state of the object, the object logo.

All objects are instances of a class, because of the support of the same behavior and family resemblance. Each object keeps the feature information, is the state of the object (if not by calling the method and change the state, the encapsulation is destroyed). The state of the object does not describe an object, each object has a unique identity.

1.3 identification

The traditional program design, should start from the main function, and the OOP program design should begin from class, and then add the method in a class. For example, the class design, a person's height, weight is the instance fields, while walking, talking is the behavior of a class. Of course, how to design a class, and not strictly in accordance with the actual conditions and the need to design, according to the specific situation specific treatment. For the class of design, it is one of the most essential part of the OOP.

Relations between the 1.4 categories

The relationship between classes, the most common are: 1 dependent (Users-A) 2 (has-a) 3 inherited polymerization(is-a).

Dependence, is one of the most significant relationship, the most common. For example, people in this category requires some specific content view personal bank information of this kind of animal, and this class is not needed, because independent and bank information. Therefore, if is a class of methods for manipulating objects of another class, we say that one class depends on another class. should be the dependency relations among classes is reduced to a minimum, if do not know the existence of a B class, it would not have any change for B B, this change will not lead to any BUG A, is what we often say that the coupling degree, minimum.

Paradigmatic relation, is an easy to understand the relationship between the. For example, the bathroom this object contains a bathtub, washbasin and other objects. Means that the object is a B object containing the class.

Inheritance, is a kind of used to represent special and general relations. For example, we design a kind of animal, inherited from the biological. In general, if a class extends the B class, so the class not only inherits the B method, may also have some own outer function.

Many programmers using the relationship between the UML class. There are many UML tools, such as Rational Rose and Together, ArgoUML, Violet etc.

2 the use of an existing class

Java, no class can't do anything. However, not all classes with object-oriented features. The Math class only function, no arguments, no data, so don't worry about generating object and initialize instance fields.

2.1 object and object variables

In Java, the use of a new instance of the constructor structure, the constructor is a special method, used to create and initialize objects. The constructor with the same class name, through the implementation of the new operator, the value returned from new is a reference.

// Defines an object variable deadline, references to objects of type Date Date deadline = new Date();

An object variable does not actually contain an object, whereas only quoted an object. To display the object variable is set to null, shows that the object variable has no reference to any object.

2.2 Java class GregorianCalendar

An instance of the Date class has a state, which is a specific point in time, the distance the number of milliseconds to a fixed time point, this point is the so-called era, UTC 00:00:00 on January 1, 1970. But the date processing provided by the Date class and not much use, the Java class library designers think: like December 31, 1999,23:59:59 such date representation is the inherent habits. However, at the same time, the Chinese Lunar New Year that's just not the same.

Library designers decided to save time and give time named separate (this is an excellent design, separate, change parts and parts do not change is similar to the MVC model, time is eternal, but give time named as view, is a kind of express way, so with such separation). So Java includes two classes: one is used to indicate the time point of Date; another is the calendar representation of class GregorianCalendar. The GregorianCalendar class extends from a more general class of Calendar class, this class describes the general properties of the calendar. The theory can extend the Calandar class to implement the lunar calendar. The use of different class represents the different concepts of , is a very good design.

// The Date class provides only a small amount of representation of time, such as before and after point in time limited sales if (today.before(birthday))     System.out.println("Still time to shop for a gift");

In fact, the Date class and the getDay method, however, the use of these is not recommended (we can see some methods painted with lines in Eclipse). When the class designers believe that a method should not exist, it is marked as not to encourage the use of(@Deprecated). Because the design that the Date time and the separation of presentation will be better, but the previous version of Date already have such method, for backward compatibility, must retain these methods (probably because many of the world's important software has been in the use of these methods, not rashly to ask others to modify the program, may introduce new errors). But when we write the program, try not to use these methods, there will be some not good place to design, but these methods are not allowed to say what day will be deleted. . .

// The new object is constructed, used to represent the date and time when the object structure GregorianCalendar gregorianCalendar = new GregorianCalendar();  // By providing the date structure of a specific time midnight calendar GregorianCalendar gregorianCalendar = new GregorianCalendar(1991, 5, 26);  // Month starting from 0, so 5 representatives in the June  // In order to avoid the problem, can use constants GregorianCalendar gregorianCalendar = new GregorianCalendar(1991, Calendar.JULY, 26);  // Also you can set the time GregorianCalendar gregorianCalendar = new GregorianCalendar(1991, Calendar.JULY, 26, 16, 26, 26);

2.3 changes in methods and accessor methods

The calendar function provides a point in time of the year, month, date and other information. If you want to query the information, you should use the get method. At the same time in order to want, need to rely on some constants in the Calendar class, such as Calandar.MONTH (in fact, I think the enumeration is better, instead of using the int constant).

GregorianCalendar gregorianCalendar = new GregorianCalendar(); int month = gregorianCalendar.get(Calendar.MONTH); // The output is 8 (I tested it is September, so it is 8, introduced before) int weekly = gregorianCalendar.get(Calendar.DAY_OF_WEEK); // The output is 3 (I tested it is Tuesday, Sunday is the 1, and so on)
// You can call the set method, change the state of an object, set for April 15, 2012 now.set(Calendar.YEAR, 2012); now.set(Calendar.Month, Calendar.APRIL); now.set(Calendar.DAY_OF_MONTH, 15);  // Also can be convenient to set the date now.set(2012, Calendar.JULY, 9);  // Also can increase the number of days for a given date, week, etc. now.add(Calendar.DATE, 1); // This was in June 10, 2012

The get method with set and add is determined by difference. The get method only view and return the state of the object, and the set and add methods to modify the state. Modified method known method for changes to , access to and shouldn't be called the accessor methods for . Accessor methods in C++ to have the suffix const, no obvious difference between Java. Usually used in front of the get prefix access method, changes with the set prefix. You can obtain a Date object through the getTime method, can also use a Date object to construct a Calander object.

2.4 simple calendar program design

This book provides a simple calendar program examples, used to describe how to use the GregorianCalendar object, print the calendar month, and * tagging current day, effect diagram as follows:

The book provides a set of design thought and the final shape of the code, but I think that is a process of learning or learning, I should write a program like this in their own way, here are some ideas I, you can.

Cheng Xuxian won the current date information and the current location calendar is used (the United States is Sunday is the first day of a week, the British Monday is the first day of the week), is also the international we say, output the calendar, then, since the first day of the month is not necessarily on the first date next, so it is necessary to have the indented format, then print the whole month day information, and marked * in the current day.

The following provides a key part of every step of implementation code

// The first day of a week is Zhou Ji area int firstDayOfWeek = calendar.getFirstDayOfWeek();  // Get an abbreviated format week head String[] weekDayNames = new DateFormatSymbols().getShortWeekdays(); // Calendar print head for (int i = 1; i <weekDayNames.length; i++) {     System.out.printf("%5s", weekDayNames[i]); }
// Calendar Settings to the first day of the month, and to determine the day of the week calendar.set(Calendar.DAY_OF_MONTH, 1); int firstDayWeek = calendar.get(Calendar.DAY_OF_WEEK);  // Determination of indentation of the day int indent = 0; while (firstDayWeek != firstDayOfWeek) {     indent++;     calendar.add(Calendar.DAY_OF_MONTH, -1);     firstDayWeek = calendar.get(Calendar.DAY_OF_WEEK); }  // Print a retracted position for (int i = 0; i <indent; i++) {     System.out.printf("%5s", " "); }
// Print the calendar content do {     int day = calendar.get(Calendar.DAY_OF_MONTH);     day = calendar.get(Calendar.DAY_OF_MONTH);     System.out.printf("%3d", day);     if (day == todayDay) {         System.out.print("* ");     } else {         System.out.print("  ");     }     calendar.add(Calendar.DAY_OF_MONTH, 1);     if (calendar.get(Calendar.DAY_OF_WEEK) == firstDayOfWeek) {         System.out.println();         System.out.print(" ");     } } while (calendar.get(Calendar.MONTH) == todayMonth);

Through these three operations, the basic can achieve some of the demand that. The program has a few key points: calendar head can not use System.out.println ("Sun   Mon  ..."); the output of this method, because each person using the area are not the same, we should, as far as possible call the general, for international to design program, such if the method itself, there is a problem, as long as the class designer to modify the program, we can be back to normal. And we designed this place, there will be a lack of consideration, and it will improve the efficiency of programming, therefore, class library and try to reuse existing, instead of writing their own. You can set the default address to test the effect of different countries: Locale.setDefault (Local.US); (this is the default for the United States of America.)

Attach the whole program I (if you see feel any wrong place, welcome.):

import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale;  /**  * Make a calendar program, display the calendar month, day and annotation  * @author S.R.ZHANG  *   */ public class MyCalendar {          public static void main(String[] args) {                  Locale.setDefault(Locale.US);         // By the date information to construct a calendar object         GregorianCalendar calendar = new GregorianCalendar();                  // This month, day information         int todayDay = calendar.get(Calendar.DAY_OF_MONTH);         int todayMonth = calendar.get(Calendar.MONTH);                  // Calendar Settings to the first day of the month, and to determine the day of the week         calendar.set(Calendar.DAY_OF_MONTH, 1);         int firstDayWeek = calendar.get(Calendar.DAY_OF_WEEK);                  // The first day of a week is Zhou Ji area         int firstDayOfWeek = calendar.getFirstDayOfWeek();                  // Determination of indentation of the day         int indent = 0;         while (firstDayWeek != firstDayOfWeek) {             indent++;             calendar.add(Calendar.DAY_OF_MONTH, -1);             firstDayWeek = calendar.get(Calendar.DAY_OF_WEEK);         }                  // Get an abbreviated format week head         String[] weekDayNames = new DateFormatSymbols().getShortWeekdays();         // Calendar print head         for (int i = 1; i <weekDayNames.length; i++) {             System.out.printf("%5s", weekDayNames[i]);         }         System.out.println();                  // Reset the current day         calendar = new GregorianCalendar();         calendar.set(Calendar.DAY_OF_MONTH, 1);                  System.out.print(" ");         // Print a retracted position         for (int i = 0; i <indent; i++) {             System.out.printf("%5s", " ");         }                  // Print the calendar content         do {             int day = calendar.get(Calendar.DAY_OF_MONTH);             day = calendar.get(Calendar.DAY_OF_MONTH);             System.out.printf("%3d", day);             if (day == todayDay) {                 System.out.print("* ");             } else {                 System.out.print("  ");             }             calendar.add(Calendar.DAY_OF_MONTH, 1);             if (calendar.get(Calendar.DAY_OF_WEEK) == firstDayOfWeek) {                 System.out.println();                 System.out.print(" ");             }         } while (calendar.get(Calendar.MONTH) == todayMonth);     } }

And attach on the books of the program:

import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.GregorianCalendar;  public class CalendarTest {     public static void main(String[] args) {         GregorianCalendar d = new GregorianCalendar();                  int today = d.get(Calendar.DAY_OF_MONTH);         int month = d.get(Calendar.MONTH);                  d.set(Calendar.DAY_OF_MONTH, 1);                  int weekday = d.get(Calendar.DAY_OF_WEEK);                  int firstDayOfWeek = d.getFirstDayOfWeek();                  int indent = 0;         while (weekday != firstDayOfWeek) {             indent++;             d.add(Calendar.DAY_OF_MONTH, -1);             weekday = d.get(Calendar.DAY_OF_WEEK);         }                  String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();         do {             System.out.printf("%4s", weekdayNames[weekday]);             d.add(Calendar.DAY_OF_MONTH, 1);             weekday = d.get(Calendar.DAY_OF_WEEK);         } while (weekday != firstDayOfWeek);         System.out.println();                  for (int i = 1; i <=indent; i++)             System.out.print("    ");                  d.set(Calendar.DAY_OF_MONTH, 1);         do {             int day = d.get(Calendar.DAY_OF_MONTH);             System.out.printf("%3d", day);                          if (day == today)                  System.out.print("*   ");             else                  System.out.print("    ");                          d.add(Calendar.DAY_OF_MONTH, 1);             weekday = d.get(Calendar.DAY_OF_WEEK);                          if (weekday == firstDayOfWeek)                  System.out.println();         } while (d.get(Calendar.MONTH) == month);                  if (weekday != firstDayOfWeek)             System.out.println();     } }

3 user-defined classes

Before we write classes, there are main method, but this is not the reality, the reality of life in the program, there is no main method. The program is constantly these kind of interaction of. The book written in a simple Employee class to illustrate some of the most basic things.

3.1 class Employee and the class of the test class

import java.util.Date; import java.util.GregorianCalendar;  public class Employee {          private String name;     private double salary;     private Date hireDay;          public Employee(String name, double salary, int year, int month, int day) { = name;         this.salary = salary;         GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);         hireDay = calendar.getTime();     }          public void raiseSarlary(double byPercent) {         double raise = salary * byPercent / 100;         salary += raise;     }      public String getName() {         return name;     }      public double getSalary() {         return salary;     }      public Date getHireDay() {         return hireDay;     } }

We prepared a test class a to test the Employee class:


public class EmployeeTest {     public static void main(String[] args) {         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);                  for (Employee e : staff) {             e.raiseSarlary(5);         }                  for (Employee e : staff) {             System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay());         }     } }

This class through the constructor, construct 3 Employee objects, and their wages are up 5%, and output the final result:

Use the javac command to compile, through javac Employee*.java can compile the two classes, because the two class names are consistent with such a format.

3.2  Analysis of the Employee class

We first analyze the methods of this class. This class contains a constructor and four method. All the methods of this class are marked to public, means that any class can call these methods. And this class has three instances, the private keyword to ensure that only the Employee class itself can access.


We first analyze the constructor, the constructor's name must be the same name as the class, when constructing object, constructor is run, in order to instantiate an object of the initial state. The use of new Employee ("S.R.ZHANG", 10000, 2013, 6, 9); the example domain settings. The constructor must pass new operator call, not directly call the constructor such as jams.Employee (...) this is wrong. Constructors are as follows:

If we are operating raiseSalary (double byPercent) this method, Such as: number001.raiseSalary (5) is double; raise = number001.salary * 5 / 100, number001.salary + = raise; this method has two parameters, The first is called implicit parameter, Appears in the method before the Employee object (number001); the second is the explicit parameters. In each method, the keyword this representation of implicit parameters, so in the constructor, I use = name; used to distinguish between the two name, the first is the example domain object name, second is the construction method of name.

We also provide three accessor methods, getName, getSalary, getHireDay, also known as domain access device . In general, we set an example for the domain, often should provide three content:

To do so to provide a simple public data domain is a bit more complicated, so many people can't understand the meaning of doing so, but this approach has obvious benefits:

1 can change the internal implementation, in addition to the class itself, does not affect the other code


// The original program public String name;  // The calling program. System.out.println(name);  // If the program change, converting name into firstName and lastName. public String firstName; public String lastName;  // The outside call to change into System.out.println(firstName + " " + lastName);  // If the use of accessor methods. private String name;  public String getName() {   return name; }  // The program was modified private String firstName; private String lastName;  public String getName() {   return firstName + " " + lastName; // Only need to modify the method and the class itself, the external call is not affected, is still the getName method }

Change the 2 device can perform error checking, and directly to the field operation is not processed

public int age; // If you want to make this age must be greater than 18 years old, you must override the validate method to verify a  // The use of modifier private int age;  public void setAge(int age) {   if (age >= 18) {       this.age = age;   } else {     System.out.println("Must be over the age of 18!");   } }

Don't write returns a reference accessor methods for variable object. The Employee class is in breach of this principle:

Employee harry = ...; Date d = harry.getHireDay(); double tenYearsInMilliSeconds = 10 * 365 * 24 * 60 * 60 * 1000; d.setTime(d,getTime() - (long)tenYearsInMilliSeconds );

Because D and harry.hireDay refer to the same object, constructor methods change can be secretly change the private calls to D. Therefore, if the reference to return of a mutable object, first to clone.

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

So, the value of D is just a and harry.hireDay itself is the same value, but refer to different places, so that the operation of D will not change the data domain private.

3.3 private methods and instance of final domain

The realization of a kind of when, because of public data is very dangerous (not others of the data domain to do the operation examination and limit any), so it should be set to private. Also, in some cases, the method is set to private . For example, this method, providing a common interface, this method is composed of a series of process, therefore, these processes, both should be set to private, the public keyword to private.

class Waiter {   // Exposed interface, greeting a new guests, including two steps to find a seat and tea   public void welcomeANewVisitor() {      searchTheSeat();      provideTea();   }    private void searchTheSeat() {     System.out.println("Hello, sit down, please!");   }      private void provideTea() {     System.out.println("Hello, this is your cup of tea, please!");   } }

If the provideTea method is modified, so when the class is processed, we can directly remove the method, because the private method we can determine the other places do not call, however, if this method is public, we can never be sure of this, this method will always exist in this class, to a troubled later ( for each set of public method is the commitment to the user).

Examples of domain can be defined as final. To construct the object must be initialized such domains. That is to say, must ensure that after each constructor execution, the value of this field is set up, and later he can not make changes. Domain final modifiers are used in the basic data types or immutable classes. If you do not change the object of each method in the class, this species is immutable classes (such as String).

For the variable type, use the final modifier is very difficult for people to understand, for example: private fianl Date hireDay; simply means that the object is stored in the hireDay reference cannot be changed in the object structure, but does not mean that the hireDay object is a constant, any method can be references to the hireDay object calls the setTime changer.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Magee at November 13, 2013 - 5:25 AM