Java study notes article 2 core technologies

Source: Internet
Author: User
Tags define abstract

Chapter 10 inheritance of interfaces, inheritance and polymorphism 10.1 (extends keyword)

1. the basic idea of inheritance is to create a new subclass based on the extension of a parent class, which can inherit the original attributes and methods of the parent class, you can also add attributes and methods not available to the original parent class, or directly rewrite some methods in the parent class.
2. you can use the super () statement to call the constructor of the parent class in the constructor of the subclass, or use the super keyword to call the member method of the parent class in the subclass, however, the subclass does not have the permission to call the method modified as private in the parent class.

Rewrite Method

3. inheritance is also acceptable.Rewrite(Also called overwrite) The member method of the parent class. Rewriting is to retain the name of the member method of the parent class in the subclass, override the implementation content of the member method, change the storage permission of the member method, or modify the return value type of the member method.

3.Reconstruction(A special rewrite method). The return value, method name, parameter type, and number of member methods of the subclass and the parent class are identical. The only difference is the method implementation content.

4. When the parent class method is rewritten, the permission to modify the method can only be changed from small to large.

5. Override the parent class of a subclass can modify the type of the return value of a method, but the type of the returned value must be a subclass of the same return value type of the parent class.

6. When the instantiated subclass object is, the parent class object is also instantiated accordingly. In other words, when instantiating a subclass object, the java compiler automatically calls the non-argument constructor of the parent class in the constructor of the subclass.

7. when a subclass object is instantiated, the non-argument constructor of the parent class is automatically called, but the constructor with parameters cannot be automatically called, only the super keyword can be used to explicitly call the constructor of the parent class.

10.2 in java, all classes directly or indirectly inherit the java. lang. Object class. It is a subclass of all classes and is the top class in the java class layer. 1. getaClass () method

It will return the Class instance when the object is executed, and then the Class name can be obtained using the getName () method.

Syntax: getClass (). getName ();

2. The toString () method returns an object as a String and returns a String instance. In actual applications, the toString () method is often rewritten to provide a specific output mode for the object. 3. the default implementation of the equals () method is to use the "=" operator to compare the reference addresses of two objects, instead of the object content. Therefore, we want to really compare the content of two objects, you need to override the equals () method in the Custom class. 10.3 conversion of Object Types 1. The upward transformation is to convert sub-classes into parent classes and use parent type references to point to child type objects for dynamic calls. The conversion between a specific class and a more abstract class. Statement: Shape s = new Circle (); 2. Convert the abstract class to a more specific class. Upward transformation is automated, but downward transformation is not. We need to force type conversion. This method is called explicit type conversion.

B B = new B ();

A a = B;

B bb = (B);// Force type conversion, that is, downward Transformation

3. analysis remembers a simple and complex rule. A type reference can only reference methods and variables contained in the reference type. You may say this rule is incorrect because when the parent class references a subclass object, the last method is the subclass method. In fact, this is not a conflict. It is because the later binding (polymorphism) is adopted. During the runtime, the compiler calls the subclass method based on the actual type indicated by the reference, if the subclass method is not defined in the parent class, compilation will fail. When you reference a subclass object using the parent class, the jvm (java virtual machine) has used the type information generated by the compiler to adjust and convert the information. As you can understand, this is equivalent to setting the methods not contained in the parent class from the virtual function table as invisible, note that some function addresses in the virtual function table may have been rewritten in the subclass, therefore, the virtual function Project address in the object virtual function table has been set as the address of the method body completed in the subclass. 10.4 instanceof determines the object type when the program performs the downward transformation operation, if the parent class object is not an instance of the subclass object, a ClassCastException occurs, therefore, before performing the downward transformation, You need to determine whether the parent class object is an instance of a subclass object. This judgment is usually done using the instanceof operator. It can determine whether a class implements an interface or whether an instance object belongs to a class. Syntax: myobject instanceof ExampleClass // reference A Class Object of myobject; reload method of a class 10.5 method of ExampleClass: Make the method name the same while the construction method of different parameters exist at the same time. It can also be applied to non-constructor methods. Class MethodOverloading {
Void receive (int I ){
} Void receive (float f) {} void receive (int I, int j) {}} In the overload, the return values of the two methods can be different, however, if the return value is different, the two methods cannot be overloaded. You need to set the number and type of parameters. 1. variable Length Parameter Method Syntax: The Return Value Method Name (parameter data type · parameter name) defines the variable length parameter in the form, the compiler will regard the form (int · a) as (int [] a), so the for loop statement is used when the add () method body performs the accumulate operation, in the loop, the length of array a is used as the cycle condition. Public static int add (int... ){
Int s = 0;
For (int I = 0; is + = a [I];
Return s;
} Public static void main (String args []) {
System. out. println ("Call the variable length parameter method:" + add (, 9 ));
} 10.6 multi-state
Polymorphism allows different types of objects to respond to the same message. Polymorphism includes parameterized polymorphism and inclusion polymorphism. The polymorphism language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, which effectively solves the same name problem of application functions.
10.7 abstract class and interface 10.7.1 abstract class (abstract keyword) public abstract class Test {// define abstract class abstract void testAbstract (); // define abstract method} 1. abstract methods do not have a method body. abstract classes have no meaning except inheritance. 2. This class is marked as an abstract class as long as there is an abstract method in the class. 3. After the abstract class is inherited, all the abstract methods must be implemented. 10.7.2 an interface is an extension of an abstract class. It can be regarded as a pure abstract class. All methods in the interface do not have a method body. 1. define interface (interface keyword): public interface drawTest {void draw (); // method in the interface, omitting abstract keyword} 2. implementation interface (implements keyword): public class Parallelogram extends Quadrangle implements drawTest {'''} 3. methods defined in the interface must be defined as public or abstract. 4. All fields defined in the interface are automatically static and final. Interfaces and inherited java do not allow multiple multi-inheritance, but multiple interfaces can be implemented at the same time. Syntax: class name implements interface 1, interface 2,..., interface n Chapter 1 advanced features of class 11th Java class Package 1. in Java, each interface or class comes from different class packages. 2. A complete class name requires a combination of the package name and class name. For example, java. util. Data3. classes in the same package access each other without specifying the package name. 11.1.1 syntax for defining the package name in the create class package class: the package name must place the package expression in the first line of the program. When the package keyword is used to specify the package name for the class, the package name will become part of the class name, indicating that the class must specify the full name. All java Package Names Use lowercase letters. 11.1.2 import class package (import keyword) 1. use the import keyword to import the package Syntax: import com. lzw. *; // specify com. all classes in the lzw package can use import com. lzw. math; // specify com. the Math class in the lzw package can be used in the program. use import to import static member Syntax: improt static member 11.2 final variable 1. the final keyword is used for variable declaration. Once the variable is set, the value of the variable cannot be changed. Statement: final double PI = 3.14; 2. In addition to modifying constants of the basic data type, final can also modify object references. 3. constants defined as final must be defined in uppercase letters and must be connected using underscores. 4. Object reference defined as final can only point to a unique object. It cannot point to other objects, but the value of an object itself can be changed. By declaring a constant as static final, you can make the constant truly unchangeable. 5. Define global constants in Java, which are usually modified using public static final. 6. Define a method parameter as the final type, which indicates that the object to which the parameter reference cannot be changed in the method. 11.3 final method 1. Defining a method as the final type can prevent any subclass from modifying the definition and implementation method of the class, and the efficiency is higher than that of non-final methods. 2. The method subclass set as the private modifier cannot be accessed. Therefore, the method defined as private is implicitly defined as the final type, and the private method does not need to be defined as the final type. 11.4 a final class defined as a final class cannot be inherited. Syntax: final class name {} if you set a class to the final form, all methods in the class are implicitly set to the final form, but member variables in the final class can be defined as final or non-final form. 11.5 If an internal class defines another class in the class, the class that is further defined in the class is called an internal class. 11.5.1 member Internal Class 1. Using an internal class in a class, you can directly access the private members of the class in the internal class. You can use the member methods and member variables of the external class at will. 2. The internal class instance must be bound to the external class instance. If an internal class object is initialized from the external class, the internal class object will be bound to the external class object. 3. External classes cannot directly access internal class member variables. The internal class instantiation operation must be implemented in non-static methods of external classes or external classes. OuterClass out = new OuterClass (); OuterClass. innerClass in = out. doit ();
OuterClass. innerClass in2 = out. new innerClass ();
2. internal class is transformed to interface 1. if a private internal class is transformed to its parent class object, or directly to an interface, the specific implementation process of the internal class can be completely hidden in the program. Only one interface and one external class are left. This is the most basic purpose of the internal class .? 2. Non-Internal classes cannot be declared as private or protected access types:
For a method, its upper layer is a class, and the upper layer is a package. Therefore, the method has the permission inherited by the class and the permission obtained by the package "inherited, and public permissions. For a class, its upper layer is the package, so a class only has the "inherit" self-package permission and public access permission, there is no concept of subclass inheritance. If a class has the permission to inherit from another class, either they have the same package or that class is public, or they have no chance to access it, let alone inherit, therefore, the subclass in protected is meaningless, while the rest of the same package only requires the default permission. Therefore, using protected is redundant.
3. Use the this keyword to obtain the reference of the internal class and the external class. If the name of the member variable defined in the internal class is the same as that of the internal class, you can use this keyword.
Public class TheSameName {private int x; private class Inner {private int x = 9; public void doit (int x) {x ++; // call the parameter xthis. x ++; // call the internal class variable xTheSameName. this. x ++; // call the external class variable x }}}
Distribution of internal class objects and external class objects in memory:


11.5.2 The local internal class can be defined in the class method or any scope .! The internal class defined in the method can only access Partial Variables of the final type. As defined in java, the internal class can only access member variables of the external class and cannot access variables defined in the method, if you want to access the variables in the method, declare the variables in the method as final (constant), because this will enable variable regionalization, which is equivalent to being defined externally rather than defined in the method.
11.5.3 Anonymous class return new A () {''' // internal class body}. After an anonymous internal class is compiled, an "external class name $ serial number" is generated. class file.

When using anonymous internal classes, remember the following principles:
· No constructor is allowed for anonymous internal classes.
· Anonymous internal classes cannot define any static members, methods, and classes.
· Anonymous internal classes cannot be public, protected, private, or static.
· Only one instance of the anonymous internal class can be created.
· An anonymous internal class must be behind new and be used to implicitly implement an interface or implement a class.
· Because the anonymous internal class is a local internal class, all restrictions on the local internal class take effect.

· Internal classes can only access static variables or static methods of external classes.

Package hqs; interface pr {void show ();} public class AdvancedPractice {// 2. create an anonymous internal public pr doit () {return new pr () {@ Overridepublic void show () in the method that returns pr in the class () {// The method stub System automatically generated by TODO. out. println ("anonymous internal Class 2") ;};} public static void main (String [] args) {// method stub automatically generated by TODO. out. println ("main function"); // 1. create an anonymous internal class new pr () {public void show () {System. out. println ("anonymous internal class ");}}. show (); // 2. instantiate the external class and use the doit () method to obtain the anonymous internal class AdvancedPractice ap = new AdvancedPractice (); pr pr1 = ap. doit (); pr1.show ();}}
11.5.4 add static before the internal class of static internal class. Features: 1. if you create a static internal class object, you do not need the object of its external Class 2. objects of non-static external classes cannot be accessed from objects of static internal classes. 3. Static members cannot be declared for non-static internal classes. 11.5.5 internal class inheritance
Public class OutputInnerClass entends ClassA. ClassB {// inherit the internal class bpublic OutputInnerClass (ClassA a) {a. super () ;}} class ClassA {class ClassB {}}
Chapter 5 Exception Handling 12th exception Overview 1. An exception is an event that occurs during program execution and interrupts the normal instruction flow of the program being executed.
2. The exception capture structure in Java consists of try, catch, and finally3. Syntax:
Try {// program code block} catch (Exceptiontype1 e) {// processing of Exceptiontype1} catch (Exceptiontype2 e) {// processing predictiontype2} · finally {// program block}
12.2 common Java exceptions
12.3 custom exceptions: the user-defined exceptions only need to inherit the Exception class. Step: 1. create a custom exception class 2. throw an exception object through the throw keyword in the method. 3. you can use the try-catch statement to capture and handle the exception, or specify the exception to be thrown to the method caller through throws in the method declaration. 4. capture and handle 12.4 throws an exception in the method 1. the throws keyword is usually used to declare a method to specify the exceptions that may be thrown by the method. Multiple exceptions are separated by commas. 2. The throw keyword is usually used in the method body and an exception object is thrown. The program is terminated immediately when it is executed into the throw statement. 12.5 runtime exception RuntimeException is generated during the program running. Exception category structure: vcyoyc/examples/MrHQVdU1 + m8/samples + HBv7y21 + m8/samples/fPtc2zo6y/samples + m8/qGxo6zL/NLAwLXT2rG + tests/tests + samples "http://www.2cto.com/uploadfile/Collfiles/20140412/20140412090753260.jpg" width = "480 "height =" 300 "alt =" \ ">
In Swing components, most GUI components are directly or indirectly subclasses of the Component class. Java's compilation of window components is related to the concepts of components and containers. 13.2 common forms 13.2.1 JFrame Forms 1. JFrame forms are a container, which is the carrier of each component in the Swing program. JFrame can be considered as a container that carries these Swing components. 2. syntax format: JFrame jf = new JFrame (title); Container container = jf. getContentPane (); 3. call the getContentPane () method to convert the form to a container, and then add components to the container or set the layout manager. For example, container. add (new JButton ("button"); 4. you can also delete the component from the container: container. remove (new JButton ("button"); 5. constructor: public JFrame () public JFrame (String title) // title form title 1. call setdefaclocloseoperation () to close the form. There are four common methods: 1. DO_NOTHING_ON_CLOSE // do not close the form. DISPOSE_ON_CLOSE // any registered listener object automatically hides and hides the form. HIDE_ON_CLOSE // hide the default window of the window closed 4. EXIT_ON_CLOSE // exit application default window close 13.2.2 JDialog form is dialog box, function is to pop up another form from one form. Similar to JFrame. Constructor: public JDialog ();
Public JDialog ([Frame f]);
Public JDialog ([Frame f], [boolean model]);
Public JDialog ([Frame f], [String title]);
Public JDialog ([Frame f], [String title], [boolean model]); // [] indicates that it may not exist, parameters are defined by the JLable class for the specified parent form, title, and mode 13.3 label components and icons 13.3.1 label (JLable, the parent class is a JCompomemt class label that can display a line of read-only text, an image, or text with an image, and does not produce the event Construction Method: public JLable ();
Public JLable (, Icon );
Public JLable (String text, int aligment );
Public JLable (Icon icon, int aligment );
Public JLable (String text, Icon icon, int aligment); // create a JLable object with text and icons, and set the horizontal alignment of the label content. you can use the Icon interface to create an Icon. You can specify the Icon size, color, and other features during creation. If you use the Icon interface, you must implement the following three methods: public int getIconHeight () // obtain the Icon length public int getIconWidth () // obtain the Icon width public void paintIcon (Component arg0, graphics arg1, int arg2, int arg3) // used for drawing at the specified Coordinate Position

2. Use the image icon

Use the javax. swing. ImageIcon class to Create Icons based on existing images

Constructor:

Public ImageIcon (); // call the setImage (Image image) method to add an Image

Public ImageIcon (Image image );

Public ImageIcon (Image image, String description); // Add a simple description for description

Public ImageIcon (URL url); // use a computer network image

13.4 common layout manager 13.4.1 absolute layout specifies the location and size of the component's container. You can use absolute coordinates to specify the component location. Step 1. use Container. setLayout (null) method to cancel layout manager 2. use Component. the setBounds () method sets the size and position of each component 13.4.2 the component is placed from left to right in the flow layout manager (FlowLayout), and moves one row down until one row occupies. 13.4.3 the border layout manager (BorderLayout) divides containers into five areas: east, west, north, and south. Add components to the five regions.
Main member variable: BorderLayout. NORTH (SOUTH, EAST, WEST, CENTER) // The component is placed at the top (bottom, right, left, and middle) 13.4.4 the grid layout manager divides the container into a grid, and the components are arranged by row and column. Constructor: public GridLayout (int rows, int columns) // int rows, int columns: Row, column public GridLayout (int rows, int columns, int horizGap, int vertGap) // horizGap, horizontal spacing. VertGap, Vertical spacing
13.5 common panel panels can be used as containers to accommodate other components, but they must be added to other containers

1 JPanel

2. JScrollPane panel with a scroll bar.

JScrollPane can only place one component, but cannot use the layout manager. If multiple components are placed, you can place multiple components on the JPanel and add the JPanel as a whole to the JScrollPane.

13.6 button component 1. JButton Construction Method: public JButton ([String text], [Icon icon]) // display text, Icon 2. JRadioButton constructor: public JRadioButton ([String text], [Icon], [boolean selected]) // set the text, icon, and whether the ButtonGroup class is selected by default to generate a button group.

3. Check box component (JCheckBox)

13.7 list component 13.7.1 drop-down list box component 1. JComboBox Class 2. the JComboBox model is an interface. There are two implementation methods: public void setSelectedItem (Object item) // you can set the selected public Object getSelectedItem () in the drop-down list box. // you can return the selected items from the drop-down list.

You can also inherit two important methods of the AbstractListModel class:

GetSize (): length of the returned list

GetElementAt (int index): returns the value at the specified index.

13.7.2 JList component JList class () constructor: public void JList () provides three methods for setting items in the list box: array, Vector, and ListModel model 13.8 text component 1. the JTextField component is used to display or edit a single line of text. constructor: public JTextField ([Document docModel], [String text], [int fieldWidth]) // you can specify the default text, text Box length 2. password box component (JPasswordField)

Constructor: public JPasswordField ([Document docModel], [String text], [int fieldWidth])

Method setEchoChar (). You can change the password box to display the characters.

3. Text domain component (JTextArea)

You can enter multiple lines of text.

Constructor: public JTextArea ([Document docModel], [String text], [int fieldWidth])

13.9 common event listeners are essentially class objects that implement listener interfaces of feature types. Events are represented by objects. All event sources have the addXXXListener () and removeXXXListener () Methods to add or remove the corresponding event listener for the component. 1. action event listener (ActionListener) generally uses anonymous internal class form when listening events for event sources. the FocusListener interface is implemented by the focus event listener (FocusListener). The foucusLost () and focueGained () methods must be used again.


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.