J2SE knowledge point summary notes (3) --- Java object-oriented Part 3

Source: Internet
Author: User

Java object-oriented Part 3


Preface


In the previous two sections, we had a similar understanding of object-oriented,

This section is also the end of the Java object-oriented part,

In this section, we will parse the abstract class, interface, modifier, enumeration, and encapsulation;





Abstract class


What is an abstract class?

We can abstract a class with common characteristics, and the method of this class does not have any specific implementation;

Eg: Define an abstract animal class, and then define several abstract methods (Methods common to animals), such as setting the number of feet

Public abstract void setFoods ();


Abstract class definition:

Modify with abstract keywords

Abstract class:Modifier abstract class name {// class content}

Abstract method:Modifier abstract return value type method name ();


Use Rules for abstract classes:

① If a class has an abstract method, the class must be an abstract class; otherwise, if a class is an abstract class, but may contain non-Abstract METHODS

② If a class inherits an abstract class, all abstract methods in the abstract class must be overwritten! All! If not all are implemented

The subclass must also be defined as an abstract class.

③ Abstract cannot be put together with static; otherwise, an error occurs (because static cannot be overwritten, abstract must be overwritten to take effect)

④ The abstract class cannot be defined as final! Abstract cannot coexist with final!

⑤ Differentiate empty implementations of methods and abstract methods

Eg: Empty implementation of the method: Abstract of the private void show () {} method, without implementation: private void show ();

6. the abstract class cannot be instantiated! However, you can rewrite the abstract method in the new method.



Example of using abstract classes

Code:

Package com. jay. example;/** the Code defines an abstract class, automobile class, and several attributes and Abstract METHODS * And then defines the passenger car and Crane class as its subclass, * The abstract method is rewritten in the passenger and vehicle categories, and the specific method is also rewritten * in the crane class, only the specific method is rewritten, and the abstract method is not rewritten. Therefore, the crane class * needs to be set as an abstract class, otherwise, an error will be reported **/abstract class Car {protected String color; protected int sudu; // define a specific method public void speed () {System. out. println ("acceleration");} // defines an abstract method, which is an empty implementation of the method. During subclass inheritance, the public abstract void useful ();} class Truck extends Car {public void speed () {System. out. println ("Truck Very slow to start ");} public void useful () {System. out. println (" trucks are used for freight! ") ;}} // Defines the Crane class. No abstract method is implemented. Therefore, you need to abstract the class Crane extends Car {public void speed () {System. out. println ("the crane is slower! ") ;}} Public class AbstractDemo {// The abstract class cannot be instantiated directly! Car c = new Car () will report an error // Of course, you can follow the upward transformation rule: Car c = new Track (); is public static void main (String [] args) {Truck tr = new Truck (); tr. speed (); tr. useful (); // The following demonstrates the effect of protected modifier. The subclass or the same package can be seen in tr. color = "white"; tr. sudu = 40; System. out. println (tr. color + tr. sudu + "km/h ");}}


Run:



Code parsing:

This Code demonstrates the basic usage of the abstract class. It defines the parent class Car of the abstract class and an abstract method and a specific method.

Then, two methods are rewritten in the truck class. In the crane class, only the specific methods are rewritten. Therefore, the crane class needs to be set as an abstract class.

Finally, the scope of protected is demonstrated: subclass is visible to the same package



Interface


Interface introduction:

Because Java's data structure is tree-like, it does not inherit multiple parent classes at the same time as C ++. However, Java implements Multi-inheritance through interfaces and internal classes.

An interface is a special abstract class. A class implements an interface, which inherits an abstract class.


Interface Definition:

Modifier inteface interface name {"content "}


Interface implementation:

A class can implement multiple interfaces while inheriting a parent class, separated ","

Class name extents parent class implements interface 1, interface 2 ...{}


Rules:

① Only one public-modified class or interface is allowed in a Java file and must have the same name as the file name !!

② In an interface, all methods are public, abstract methods !! All attributes are public, static, and constant!

③ If a class declaration implements an interface but does not implement all methods in the interface, the class must be an abstract class!

④ The interface only cares about functions and does not care about specific functions.

⑤ Interfaces can also be inherited through extends! However, we still need to implement all the abstract methods in the sub-interface and parent interface.

⑥ Methods in the interface can be written without public, but public must be written when the subclass implements the abstract methods in the interface. Otherwise, an error will be reported!


Sample Code:


Package com. jay. example;/** in this code, we define two parent interfaces, and use a subinterface to inherit the two parent interfaces * and define an abstract method for the subinterfaces; then define a Person to implement two parent interfaces * override two abstract methods, and define a Worker to implement sub-interfaces, however, you also need to overwrite the abstract method in the parent interface * *** // define an interface Speak {void speak ();} // define an interface for eating Eat {void eat () ;}// define a subinterface and inherit the interfaces for speaking and eating at the same time, at the same time, define a walking method interface Walk extends Speak, Eat {void walk () ;}// define a Person class to implement the interface for speaking and eating, override the abstract method in the interface // when the subclass implements the interface, the public modifier cannot be omitted, otherwise the class Person implements Speak, Eat {public void speak () {System. out. println ("Person class can talk");} public void eat () {System. out. println ("Person class can eat") ;}// defines a Worker class to directly implement the walk interface, at the same time, the abstract method class Worker implements Walk {public void speak () {System. out. println ("Worker class can talk");} public void eat () {System. out. println ("Worker class can eat");} public void walk () {System. out. println ("Worker class walking");} public class InterfaceTest {public static void main (String [] args) {// instantiate two objects, output corresponding result Person p = new Person (); p. eat (); p. speak (); Worker w = new Worker (); w. eat (); w. speak (); w. walk ();}}

Code:



Code parsing:

This Code demonstrates interface inheritance and interface implementation

It's relatively simple. I skipped it here.



Detailed description of the modifier Access Control Modifier

Public:Public, public-modified parts can be accessed by any program

Protected:Protected, the modified members can only be accessed by the class or its subclass in the same package.

Default (default ):If you do not write modifiers, they are the default ones. Do not write defalut! Same package and similar visible

Private:Private is the key to Java encapsulation. The modified member variables and methods can only be accessed by the class itself, and cannot be accessed by the same package!


Note:

The protected and private modifiers cannot be used; either public or without any Modifiers


Other modifiers: static Modifier

① Static variables:

The data shared by all objects with static modified variables points to the same address in the memory.

That is, any modification to the object will change the value of the bucket.


Code Demonstration:

Package com. jay. example; class Test {// define the initial value as 3 static int a = 3;} public class StaticTest {public static void main (String [] args) {// static member variables can be accessed directly by class names. out. println (Test. a); // instantiate two objects. Modify the value of a in t1 and find that the value of a in t2 also changes Test t1 = new Test (); t1.a = 4; test t2 = new Test (); System. out. println (t2.a); // The output result is: // 3 // 4 // It indicates that static variables are in a common memory area and any object // modifies the value, will change the value of the corresponding memory area }}

② Static method:

Note:

In static methods, you can only access static data or directly call static methods.

You can call it by class name directly.

Code Demonstration:

Package com. jay. example; /** because our main method is a static method *, we define parameters and Methods outside the main method * to verify that static methods can only access static members */public class StaticTest2 {/ /define non-static data and method int a = 3; void test () {System. out. println ("non-static methods can not be called by main");} // defines static data and method static int B = 4; static void test2 () {System. out. println ("the static method is called by main");} public static void main (String [] args) {// The following two statements. If yes, an error is returned, believe it or not, try // System. out. println (a); // test (); System. out. println (B); test2 ();}}

③ Static code block

Placed inside the class declaration, outside the Member method and constructor method, this code block will be used for the first time of this class

Once executed, it will not be executed again. It is usually written here with some initialization code.

Code Demonstration:

Package com. jay. example; public class static3 {static {System. out. println ("static code block, usually used for class initialization ");}}

④ Complex member initialization Problems

What is the initialization sequence of static data, static code blocks, object members, and constructor?

In fact, the initialization sequence is: (static variables, static initialization blocks) ---> (variables, variable initialization blocks) ----> Constructor

The following code verifies this rule:

Package com. jay. example; public class static3 {public static String staticStr = "static member initialization"; public String str = "common member initialization"; // constructor public static3 () {System. out. println ("constructor initialization");} // common initialization block {System. out. println (str); System. out. println ("normal initialization block");} // static initialization block static {System. out. println (staticStr); System. out. println ("static initialization block");} public static void main (String [] args) {static3 st = new static3 ();}}

Run:




Final: final Modifier

Usage


① Use final to modify attributes (variables). The attributes are constants. Use public static final int AGE = 10 in Java to identify constants.

② Blank final variable (not initialized): blank final data members must be initialized in the constructor; otherwise, an error is reported.

③ As a method parameter, a final constant can only be referenced in a simple way, and the value of a constant cannot be changed!

④ Use final to modify the method: This method is a method that cannot be overwritten. If the parent class has a final modification method, the subclass inherits the same method.

⑤ Use final to modify the class: the class cannot be inherited, and the final class has no subclass. All methods in this class are final by default.

6 final does not involve inheritance. Inheritance depends on whether the class modifier is public or other. Whether the class can be inherited depends on whether the class is visible to its subclass.

If a method has a private or static modifier before it, the system automatically adds the final modifier before it.



Abstract: abstract Modifier

The class modified by abstract is an abstract class, and the modification method is an abstract method.


Transient:

Used to modify members that do not want to be serialized or persisted


Volatile:

It ensures visibility and prevents re-sorting. It is used for a relatively small number of concurrent operations.



Enumeration type analysis:

① As the enumeration introduced after jdk 1.5, used to replace the public final static

② It is represented by enum, and its function is similar to the class keyword;

③ Do not modify the constructor using public.

④ Variables and methods must be defined after enumeration values !!!



Example: simple enumeration:

Package com. jay. example;/** this program demonstrates the simplest use of enumeration * defining that enumeration Color has three values, demonstrate all original methods in switch and enhanced for loop traversal enumeration */enum Color {BLUE, RED, YELLOW;} public class EnumTest {public void printColor (Color color) {switch (color) {case BLUE: System. out. println ("output blue! "); Break; case RED: System. out. println (" output RED! "); Break; case YELLOW: System. out. println (" output YELLOW! "); Break ;}} public static void main (String [] args) {EnumTest test = new EnumTest (); test. printColor (Color. BLUE); test. printColor (Color. RED); test. printColor (Color. YELLOW); // Of course, you can also use an enhanced for loop to traverse all values in the enumeration: // you can obtain the enumerated array for (Color c: Color. values () {System. out. println (c );}}}

Run:




Further steps:

Package com. jay. example;/** this Code demonstrates the further use of enumeration classes. * like a class, enumeration can define its own attributes and methods, but * must be written after the enumeration list, otherwise, a compilation error will be reported. **/public class EnumTest2 {public enum Color {// enumeration can be used to add methods and properties like ordinary classes Red ("Red "), BLUE ("BLUE"), YELLOW ("YELLOW"); // constructor, do not write public modifier! Color (String value) {this. value = value ;}// define a member variable private final String value; // define a method to obtain the value following the public String getValue () {return value ;}} public static void main (String [] args) {EnumTest2 test = new EnumTest2 (); // you can obtain all the values in the for (Color color: Color. values () {System. out. println (color); System. out. println (color. getValue ();} // you can use ordinal to obtain the index position of the enumerated value in the enumeration, starting from 0. out. println (Color. BLUE. ordinal (); // the java. lang. comparable interface, you can directly call compareTo to compare the enumerated values // here Red is before Blue, so it is-1System. out. println (Color. red. compareTo (Color. BLUE ));}}

Run:

To consolidate the programming, you have to do more relevant programming questions, and you will remember the knowledge points!


If any omission or error occurs in the text, please kindly advise. Thank you very much !! (* ^__ ^ *) Xi ......

















Related Article

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.