Java cafe (8)-big talk object-oriented (II)

Source: Internet
Author: User

When I thought about this cafe, the Olympic torch burned. Seeing the efforts of the Chinese Olympic Delegation to win glory for the country, I couldn't help but decide to dedicate this topic to our Olympic athletes! Object-Oriented Programming

If you are a regular visitor to the Java cafe, you have been familiar with and applied Java object-oriented knowledge before you even knew it. In this cafe, let's analyze an object-oriented programming instance in detail to consolidate the knowledge.

Olympic Games are an international sports event. Chinese athletes must be named in English to facilitate international connection. The program to be compiled this time is a tool for parsing English names. Generally, an English name such as Gary Chan indicates that the name is first and last. In the form of Yao and Ming, the last name is behind the previous name. You should never think that Gary was here to advertise with Yao and Ming for no reason. When Yao was in junior high school, he was in a class with Gary. After he was turned up and cried, gary often comforted him and rode home together. Seeing that Yao is already a world-class athlete, Gary needs to work harder ......

OK, let's get down to the truth. Our program will automatically judge the name form and break down the surname and name. Still, use Eclipse to generate a project named Chap 07 NameParser, add a new NameParser class, and fill in com. cfan. garychan. nameparser in the Package attribute. If you forget the package knowledge, refer to the package concept description in Java cafe (6)-develop a guess digital game.

A class is a template that defines the relationship between data and methods in an instance generated from the class. Some people like to make an analogy as an image. The image produced by the image is an object.

The class keyword is used in Java to define the class, but it is more convenient to use Eclipse to define the class. I still use Eclipse to create a new class named Namer. Remember not to check it before public static void main (String [] args). After confirmation, Eclipse will generate a new Java source file named Namer. java, the Code is as follows:

public class Namer {

}

This class is very simple, but unfortunately it cannot do anything.

  1. Encapsulation

An important technology in Object-Oriented Programming is encapsulation, which encapsulates objective things into abstract classes, classes can only perform trusted class or object operations on their own data and methods to hide untrusted information. The benefit of doing so is that you can make the specific implementation of the class transparent, as long as other code does not depend on the private data within the class, you can modify the code with ease. In addition, this is also out of security considerations. If the variables representing the online payment card password can be accessed at will, who would dare to use such a system?

Encapsulation mainly relies on access control for classes, data, and methods. In terms of syntax, keywords such as private, protected, and public are added. If there is no keyword modification, the default value is package. Their control permissions are shown in the following table:

Specifier subclass package world
Private X
Protected X * X
Public X
Package X

Note that in X * above, the protected part of the parent class can be accessed only by the Child class in the same package as the parent class. Otherwise, it is not accessible.

Let's take a look at the instance. Slightly change the Namer class:

Public class Namer {
Protected String surname; // surname
Protected String firstname; // name

Public String getFirstname (){
Return firstname;
}

public String getSurname() {
return surname;
}
}

This class has two member variables of the String type, surname and firstname, which are used to store the last name and name respectively. The two member variables have the protected modifier. According to the table, these two variables can only be operated by the class itself, subclass, and other classes in the package, while the classes outside the package are not authorized to access them. However, to communicate with the code outside the package, the Namer class provides the getFirstname and getSurname public methods. Therefore, name data is read-only for classes outside the package.
2. Inheritance

Objects are defined by classes. Through the class, you can fully understand the full picture of the object. For example, when talking about a bicycle, you will think that the bicycle has two wheels, handlebars and pedals.

Furthermore, another feature of object-oriented language is to allow new classes to be defined from an existing class. For example, mountain bikes, highway racing cars, and two-person Tricycles are bicycles. In the object-oriented language, you can define mountain bikes and road racing vehicles from an existing bicycle category. Mountain bikes and road racing vehicles are called Bicycle subclasses. bicycles are their parent classes, and such a defined relationship is the inheritance relationship.

Subclass inherits the attributes of the parent class. For example, mountain bikes and highway racing cars all have two wheels and one seat. Sub-classes can also inherit the parent class method, such as mountain bikes, highway racing cars, and two-person tricycles can both forward, brake, and turn.
Of course, subclasses are not limited to inheritance, but can also be carried forward. For example, a tricycle breaks down the attributes of a bicycle with only two wheels and one seat cushion, making itself more casual and chic.

Let's take a look at how to use inheritance to deal with the pattern before the first name. In this mode, because the surname and name are separated by spaces, the program is as follows:

Class FirstFirst extends Namer {
Public FirstFirst (String s ){
Int I = s. lastIndexOf (""); // search for spaces
If (I> 0 ){
Firstname = s. substring (0, I). trim ();
Surname = s. substring (I + 1). trim ();
}
}
}

The FirstFirst class inherits the Namer class using the extends keyword. There is only one class method named FirstFirst. This is not a coincidence.

All Java classes have several special methods used to initialize objects. They are called constructor. The feature is the same name as the class and can contain or have no parameters. This phenomenon of different parameters of functions with the same name is called Overload in object-oriented systems ). Take the code that used to generate a random number using the new operator as an example:

Random random = new Random();

After the new operator instantiates a Random object, it calls the constructor of the Random class for initialization, but this constructor has no parameters. A constructor without parameters is called a default constructor. The default constructor is owned by each class. Even if it is not declared in the Code, the Java compiler will automatically add it during compilation.

Let's look back at the FirstFirst class. The FirstFirst class inherits from the Namer class and also has its own firstname and surname attributes. In the FirstFirst constructor, parse the parameter s and use the space search method to parse the name before and after the space to execute

FirstFirst parser = new FirstFirst("Gary Chan");

After that, my surname and name have been resolved and saved in the firstname and surname variables respectively. At the same time, the FirstFirst class inherits the Namer method, so that you can use the following statement to return the surname-Gary:

String mySername = parser.getSurname();

Note that the getSurname () method is not defined in the FirstFirst class, which is inherited from the parent class. This is the concept of code reuse, avoiding unnecessary repetitive work.

With the above foundation, write the mode after the first name is the last name:

Class FirstLast extends Namer {
Public FirstLast (String s ){
Int I = s. indexOf (","); // search for a comma
If (I> 0 ){
Surname = s. substring (0, I). trim ();
Firstname = s. substring (I + 1). trim ();
}
}
}

It can be seen that the two sub-classes of the Namer class have all their attributes and methods, and the name resolution capability is added to them, but the code is not added much. Code reuse is one of the main charm of object-oriented development!
3. Polymorphism

Now, we have written two classes for the two name resolution methods, namely the FirstLast class and FirstFirst class. To better use these two classes, let's have some tips.

First, the name parser user does not care about whether to use the Namer class, the FirstLast class, or the FirstFirst class. It is best to automate these things, as long as he can get his surname and name.
Secondly, if you are an IT young man who is brave enough to handle things, you will find Namer. in java, only the Namer class is public, and the FirstFirst class and FirstLast class are not modified before -- they are the default package, that is, in com. cfan. garychan. the nameparser package cannot be accessed.

It would be nice if I could only use the Namer class to parse the name!

In fact, using the concept of polymorphism will solve these problems.

Object-oriented has three features: encapsulation, inheritance, and polymorphism. The so-called encapsulation means to abstract the essential features of a thing by defining the class and adding access control to the class attributes and methods. Inheritance means code reuse. While polymorphism, from another point of view, the interface faded dizheng window was selected. Cut the foundation, baked ting, and Yu Wei, stretched the reef, and threw on the foundation. vulgar pregnancy harmony file na Bo Miao Jiao Yu <Kai Yu Tuan Yu Cai Yu tomb Wei Xiao Yan Bao Yu yi Huai yi Hui Huan HUan Yu? Brake now! After carefully understanding this sentence, you only know that a bicycle can brake, So let a friend press the brake to brake the bicycle, rather than think that the jetant brand road racing car brakes quickly! Therefore, we are thinking about abstract
The brakes of a bicycle, but the final action is the brakes of A jetant road racing car. The class refers to an instance. This is the concept of polymorphism.

Looking back at our program, the public Namer class is exactly the common parent class of the FirstFirst class and the FirstLast class. The concept of application polymorphism is too suitable. Create a new class named NameFactory and put the class in the com. cfan. garychan. nameparser package. The Code is as follows:

public class NameFactory {
public static Namer getNamer(String entry) {
if (entry.indexOf(",") >0)
return new FirstLast(entry); //return one class
else if (entry.indexOf(" ") >0)
return new FirstFirst(entry); //or the other
else
return null;
}
}

The NameFactory class has only one static method getNamer. Note that A Namer class is returned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.