Java's seven advanced class design

Source: Internet
Author: User
Tags arithmetic pow

Use of static

Sometimes you want to define a class member so that its use is completely independent of any object of that class. Typically, a class member must be accessed through the object of its class, but it can create a member that can be used by itself without referencing a particular instance. Such a member can be created by adding the keyword static (static) before the member's declaration.

If a member is declared static, it is able to be accessed before any object of its class is created, without having to reference any object. You can declare methods and variables as static. The most common example of a static member is main (). Because main () must be called when the program starts executing, it is declared as static.

A variable declared as static is essentially a global variable. When declaring an object, the copy of the static variable is not produced, but all instance variables of the class share the same static variable.

The method declared as static has the following limitations:

· They can only invoke other static methods.

· They can only access static data.

· They cannot refer to this or super in any way (the keyword super is related to inheritance, as described in the next chapter).

If you need to initialize your static variable with a calculation, you can declare a static block that executes only once when the class is loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

Demonstrate static Variables,methods,and blocks.

Class Usestatic {

static INTA = 3;

Static INTB;

static voidmeth (int x) {

System.out.println ("x =" + x);

System.out.println ("a =" + a);

System.out.println ("b =" + B);

}

static {

System.out.println ("Static block initialized.");

b = A * 4;

}

publicstatic void Main (String args[]) {

Meth (42);

}

}

Once the Usestatic class is loaded, all static statements are run. First, A is set to 3, then the static block executes (prints a message), and finally, B is initialized to a*4 or 12. Then call Main (), main () call meth () and pass the value 42 to X. The 3 println () statements refer to two static variables A and B, and the local variable x.

Note: Referencing any instance variable in a static method is illegal.

The following is the output of the program:

Static block initialized.

x = 42

A = 3

b = 12

Outside of the classes that define them, static methods and variables can be used independently of any object. This way, you can just add the number operator to the name of the class. For example, if you want to invoke a static method from outside the class, you can use the following common format:

Classname.method ()

Here, ClassName is the name of the class, and the static method is defined in the class. As you can see, this format is similar to calling a non-static method through an object reference variable. A static variable can be accessed in the same format-the class name dot number operator. This is how Java implements a control version of global functionality and global variables.

Here is an example. In main (), the static method CallMe () and the static variable B are accessed outside their classes.

Class Staticdemo {

static INTA = 42;

static INTB = 99;

Static Voidcallme () {

System.out.println ("a =" + a);

}

}

Class Staticbyname {

publicstatic void Main (String args[]) {

Staticdemo.callme ();

System.out.println ("b =" +staticdemo.b);

}

}

The following is the output of the program:

A = 42

b = 99

Using the final keyword

A variable can be declared final, and the purpose is to prevent its contents from being modified. This means that when declaring the final variable, you must initialize it (in this usage, final is similar to the const in C + +). For example:

final int file_new = 1;

final int file_open = 2;

Final int file_save = 3;

Final int file_saveas = 4;

Final int file_quit = 5;

The subsequent parts of your program can now use File_open and so on, as if they were constants, without worrying about their values being changed.

Selecting uppercase for all the characters of the final variable is a common coding convention. A variable that is declared final does not occupy memory in the instance. Thus, a final variable is essentially a constant.

The keyword final can also be applied to a method, but its meaning and its use for variables are essentially different. The second use of final will explain inheritance in the next chapter.

Java Enumeration

As a new keyword introduced by Sun, Enum looks like a special class, it can also have its own variable, can define its own method, can implement one or more interfaces. When we declare an enum type, we should be aware of some of the characteristics of the enum type.

1. It cannot have a public constructor, which ensures that the client code has no way to create an instance of the enum.

2. All enumerated values are public, static, final. Note that this is only for enumeration values, and we can define any other type of non-enumeration variable as you would define a variable in a normal class, which can use any modifier you want to use.

3. Enum implements the Java.lang.Comparable interface by default.

4. The enum contains the ToString method, so if we call Color.Blue.toString (), the string "Blue" is returned by default.

5. Enum provides a valueof method that corresponds to the ToString method. Calling valueof ("Blue") will return Color.Blue. So we have to be aware of this when we rewrite the ToString method, which should be a relative rewrite of the valueof method.

6. Enum also provides the values method, which allows you to easily iterate through all of the enumeration values.

7. Enum also has a oridinal method that returns the order of enumeration values in the enumeration class, which depends on the order in which the enumeration values are declared, where Color.Red.ordinal () returns 0.

1. Iterates through all the enumerated values. Knowing the values method, we can pro with the Foreach Loop to iterate over the enumeration values.

For (Color c:color.values ())
System.out.println ("Find value:" + C);

2. Define methods and variables in the enum, such as we can add a method to color to randomly return a colour.

public enum Color ... {
Red,
Green,
Blue;

/**//*
* Defines a variable that represents the number of enumeration values.

* (I'm a little surprised why Sun doesn't provide an enum with a size method directly).

*/

private static int number = Color.values (). length;

/** *//**

* Random Return of an enumeration value

@return a random enum value.

*/
public static Color Getrandomcolor () ... {
Long random = System.currenttimemillis ()% number;
switch ((int) random) ... {
Case 0:
return color.red;
Case 1:
return color.green;
Case 2:
return color.blue;
Default:return color.red;
}
}
}

It can be seen that there is no difference between defining variables and methods in an enumeration type and defining methods and variables within a normal class. The only thing to note is that the variables and method definitions must be placed after all the enumeration value definitions, or the compiler will give an error.

3. Load (override) ToString, valueof method.

We already know that Enum provides methods such as tostring,valueof, and many times we need to override the default ToString method, so what do we do with enums? In fact, this is no different from the ToString method of loading a normal class.

....

Public String toString () ... {
Switch (This) ... {
Case Red:
return "Color.Red";
Case Green:
return "Color.green";
Case Blue:
return "Color.Blue";
Default
Return "Unknow Color";

}
}....

At this point we can see that the previous traversal code is then printed out

Color.Red
Color.green
Color.Blue
Instead of
Red
Green
Blue.

You can see that ToString is actually covered. In general, we should also review the valueof method in order to maintain their mutual consistency when we load the ToString.

4. Use the constructor function.

Although enum can not have a public constructor, we can still define the private constructor, which is used inside the enum. Or the example of color.

public enum Color ... {
Red ("This is Red"),
Green ("This is Green"),
Blue ("This is Blue");

Private String desc;

Color (String desc) ... {
THIS.DESC = desc;
}

Public String GetDesc () ... {
return THIS.DESC;
}
}

Here we provide a descriptive message for each color

public enum Color ... {
Red ... {
Public String toString () ... {
return "Color.Red";
}
},
Green ... {
Public String toString () ... {
return "Color.green";
}
},
Blue ... {
Public String toString () ... {
return "Color.Blue";
}

};
}

, and then define a constructor to accept this description.

Note that the constructor cannot be public or protected, so that the constructor can only be used internally, and the client code cannot new an instance of the enumeration value. This is perfectly reasonable, because we know that the enumeration value is a constant of publicstatic final.

5. Implementing a specific interface

We already know that an enum can define variables and methods, and that it implements an interface as well as an interface to an ordinary class, and this is not an example.

6. Defines the method that enumerates the values themselves.

Before we see that we can define some methods for enum, we can even define a method for each enumeration value. Thus, the example of the ToString that we have previously covered can be rewritten as such.

Logically this is clearer than providing a "global" ToString method.

In general, the enum as a completely new type of definition, is to help programmers write the code more simple and understandable, the personal feel generally do not need to use too many of the advanced features of the enum, otherwise, and easy to understand the original intention to violate.

Java static Import

Starting with jdk5.0, import not only imports classes, but also imports static methods and static fields.

If you add an import static java.lang.system.* at the top of the source file;

You can then use the static and static fields of the system class without having to add class prefixes such as:

Out.println ("Hello World"); Equivalent to System.out.println ("HelloWorld");

Exit (0); Equivalent to System.exit (0);

There are two practical applications for static methods to import and import static domains:

1. Arithmetic function, use static import to math class, can use arithmetic function more naturally

sqrt (POW (x,2) +pow (y,2));

2. Bulky constants, if you need to use a large number of constants with lengthy names, you should use static import

Date d = new Date ();

if (D.get (day_of_week) = = MONDAY)

Looks better than

if (D.get (calendar.day_of_week) = = Calendar.monday)

Clear

Code:

Import static Java.lang.Math.pow;

Import static java.lang.Math.sqrt;

Import static java.lang.System.out;

Import static Java.util.Calendar.MONDAY;

Import Java.util.Date;

public class Staticimporttest {

/**

* @param args

*/

public static void Main (string[] args) {

Out.println ("Hello");

int x = 5,y=10;

Double d = sqrt (Pow (x,2) + POW (y,2));

Out.println (d);

Date date = new Date ();

if (date.getday () = = MONDAY)

OUT.PRINTLN ("Today Week 1");

else{

Out.println ("Today's Week" + Date.getday ());

}

}

}

Using the final keyword

The Java language promises to have something called an abstract method, and he is just a name without a specific implementation. Like this: public abstract void ABC (); Uses the abstract key word, ending with ";". The methods we use in the previous sections are concrete methods and are implemented. Even if nothing in the method body is written public void abc () {} is also a concrete method.

Concept: A class that contains one or more abstract methods is called an abstract class. Abstract classes must also declare the abstract key word. The use of abstract classes has some limitations and cannot create instances of abstract classes. If the subclass implements an abstract method, you can create an instance object of the subclass. If the subclass is not implemented, the subclass is also an abstract class and cannot create an instance.

What is the interface? An interface is a class that is more abstract than an abstract class. Example: public interface Name {} The methods inside the interface are all abstract, the variables inside are all final constants, and the class that implements the interface must implement all of the abstract methods. Abstract classes can also have specific methods. So, the interface is the most abstract, followed by the abstract class, and the concrete class itself is the abstraction of the real world. Software development itself is to abstract the real world into the computer world.

Because abstract classes and interfaces are abstract than concrete classes, they are always implemented when used. But the continuation of their class is not just one, there are many classes that implement their abstract methods. There are many ways to implement a method, which uses the polymorphism in OOP. This makes the design very clear. Because the base class is an abstract class or an interface to do a description, there are several classes to continue below, we only need to operate on interfaces or abstract classes, and no need to control how many implementations. If it is a project developed jointly by many people, it is very meaningful. You write a thing yourself, how to realize also do not have to tell others, others look at an interface is enough.

The implementation of the interface is implement instead of extends with the key word. If extends is used, it is to continue this interface. Then that sub-class is also the interface, which is the original sub-interface. Give an example of an interface:

Practice:

Declaring an interface

Public interface Say {

public void Saymessage ();

}

Two implementation classes

public class SayHello implements Say {

public void Saymessage () {

System.out.println ("Hello");

}}

public class Sayhi implements Say {

public void Saymessage () {

System.out.println ("Hi");

}}

This is a test class

public class Testsay {

public static void Main (string[] args) {

It also uses say as an instance of the interface type, but can output two results

Say Say = new SayHello ();

Say.saymessage ();

Say say1 = new Sayhi ();

Say1.saymessage ();

}}

Interface also has an important role to play in the object-oriented class, we have mentioned a concept, the Java language only a single continuation, that is, only from a parent class to continue. The advantage of a single continuation is that once you continue too much, changing a subclass of class will change. Take a pitch and move your body. So what if we want to continue with the attributes of multiple parents? Just use the interface bar, this class can continue a class, and then to implement other interfaces, the interface is an abstract method, will not cause, pull a pitch, and moving the whole body effect. Changing the features of multi-continuation is also an improvement to the C + + language.

The industry has a saying that Java is not so much about object-oriented programming as it is interface-oriented programming. The emphasis is on the abstract description of the interface. It is also an improvement to C + +, there is no interface in C + +. So the Java language is suitable for multi-team cooperation of large projects, look at an interface can be, how to implement the later can be no matter.



Practical questions:

1. In the real world, are public goods in places where everyone can see or find them, and what are the similarities and differences between the static and the key words we learn?

2. There are certain things in life that are fixed, such as legal systems that have been constant for many years, and what are the similarities and differences between the final and the key words we have learned?

3. If a building is to be built, the blueprint must be designed first, then the framework of the theme will be set up, and then the detailed work will be done in detail; Finally, a building is built; what is the relationship between these steps and our software engineering?



Summary:

In this chapter, we have mainly studied:

u keyword static, final and related applications;

U Java enumeration type;

u java static Import

U abstract class and interface usage



English vocabulary:

English full text Chinese

The static statics

Final Final End

enum enum enum

Import Imports



Practice Items:

To summarize the means of fire and the apparatus of fire, such as fire extinguishers (often fixed positions), lighters (often used), kindling (classic sacred) used by primitive people, and so on, which can be summed up in the enumeration of the adjective sinks of people's fires; for example: Fengfenghuohuo, too hectic, etc., and the inheritance of human evolution ; Write the relevant code with the knowledge of object-oriented and the abbreviation of this chapter;

Java's seven advanced class design

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.