Java Small white Dry Shop (iv)

Source: Internet
Author: User
Tags constant definition

Object-Oriented programming learning notes

I. Flexibility of correspondence-polymorphism

Polymorphism means that for a service function, it can be implemented in different ways, that is, multiple forms. The polymorphic image describes the complex pattern of the real world, which makes the program have good expansibility. On the basis of inheritance, the overloading of methods is one of the ways to implement polymorphism.

Focus:the ToString () and equals (Object obj) methods of the object class.

1. The ToString method, whose return value is of type string, describes information about the current object. If a reference to an object is printed directly , the ToString () method of the object is called by default, and the default print contains the memory address that the reference points to. However, you can override the ToString method based on user customizations.

2. The Equals method of the object class is:

X.equals (y)

returns False when X and Y point to the same address to return ture. That is, a reference to two objects is compared.

3. The Equals () method of the string class compares the byte-character contents of the current object.


Two. Polymorphism is another feature of object-oriented programs derived from encapsulation and inheritance.

Manifestations of polymorphism:

    1. Method angle: Overloading and overriding of methods.

    2. From the angle of the object: divided into two kinds.

    • Transition up: Parent object, subclass object (program AutoComplete)

Format: Parent class Parent Class object = Child class instance

Description: After an upward transformation, the new method defined in the subclass cannot be found because the parent class object is being manipulated, but if the subclass overrides a method of the parent class, the overridden method is called.

Student stu=new Student ();   Person Per=stu; Upward transformation Per.say ();

    • Down Transformation: Child class object, parent object (must explicitly indicate the subclass type to be transformed)

Format: Subclass Sub-class object = (target object) parent class instance

Description: Before you go down, you need to move up .

Person Per=new Student ();   Upward Transformation Student stu= (Student) per; Downward transformation Stu.learn ();

intanceof Keywords : In Java, you can use the INTANCEOF keyword to determine whether an object is * * * An instance of a class. where * * belongs to the * * Two meaning, one is similar to the role of "demon mirror" to see whether it belongs to a certain class, and the other is to use their own objects to view their own classes.

Person P=new Student ();    SYSTEM.OUT.PRINTLN (P instanceof person); Determine if p is a person type

Final keyword : When declaring classes, properties, and methods in Java, you can use final to decorate them.

Note: 1.final modifier variables (member variables or local variables) become constants and can only be assigned once.

Private final String name= "Zhang San";

2.final decoration method, the method cannot be overridden by a quilt class.

Public final void Walk () {System.out.println ("Man walks with two legs ~ ~ ~"); Final Decoration Method}

3.final decorated class that cannot be inherited by this class.


Three. Abstract class

Definition: A class that is decorated with abstract is an abstract class.

Format:

Abstract class Name {}

1. Abstract classes cannot be instantiated and must be inherited. The abstract method must be overridden to generate its subclasses. The method that is modified by abstract is an abstract method, and there is no method body for abstract methods.

Public abstract class Animal {private String name;      Private String food;  Public Animal () {} publicly Animal (string name, string food) {this.name = name;   This.food = food;   } public abstract void Eat (); Abstract method only declares, does not implement}

2. Abstract classes do not necessarily contain abstract methods, and if the class contains abstract methods, the class must be defined as an abstract class. The Kawai class is also an abstract class, you can not override the parent class abstract method.

If the subclass is also an abstract class, you can not override the abstract method of the parent class public abstract class Tiger extends animal{public abstract void Run ();}

Four. Interface

Definition: is a collection of definitions of abstract classes and constant values . (no constructor method) interface is a "standard", "contract".

Essentially, an interface is a special kind of abstract class. This abstract class can only include definitions of constants and methods, without the implementation of variables and methods.

Statement:

[Public] Interface InterfaceName [extends listofsuperinterface]{
}

Interface Body: constant definition

Type Name = value;

The constant is shared by multiple classes that implement the interface, with the Public,static,final property.

/** * Flight Interface */public interface Fly {public static final int speed=200;   Constant public abstract void fly (); }

Interface implementation classes: As with abstract classes, interfaces must be used as well through subclasses, and subclasses implement interfaces through the Implements keyword.

public class Kite implements fly{@Overridepublic void Fly () {System.out.println ("kite fly ...");}}

Five. Character string related classes

    1. String class

      (1) The string represents the type of character, and the contents of the string are immutable, and the string exists in the string constant pool .

      There are two forms of string object creation in Java, one for literal form, such as String str = "Hello", and the other is to use new as a standard method of constructing objects, such as String str = new string ("Hello"); There are actually some differences in performance and memory usage between the two implementations. It all started with the JVM. to reduce the duplication of string objects , it maintains a special memory, which is a constant pool of strings.

show how to use the new standard constructed object, at the bottom of how it is implemented:


Common methods for 2.String classes

(1) public String (byte[] bytes)

Converts a byte array to a string using the platform's default character set decoding


(2) public String (byte[] Bytes,charset Charset)

Converts a byte array to a string using the specified character set decoding


(3) public char charAt (int index)

Get a character in a string based on the index location


(4) Public boolean contains (Charsequence s)

Determines whether the string represented by the current object contains the contents of a parameter string


(5) Public boolean equals (Object anobject)

Determine if string contents are the same


(6) Public byte[] GetBytes ()

Convert a string to a byte array


(7) public int indexOf (String str)

Returns the index position of the argument string in the current string


(8) public int lastIndexOf (String str)

Looking up the argument string, returning the index position of the argument string in the current string


(9) public int Length ()

Returns the length of the current string


(one) public String tolowercase ()

Convert a string to lowercase


Public String toUpperCase ()

Convert a string to uppercase


Public char[] ToCharArray ()

Convert a string to a character array


Public String substring (int beginindex)

From the Beginindex index position, to the end of the string, to intercept the string


Public String substring (int beginindex,int endIndex)

From Beginindex index position, to endIndex-1, intercept string


(+) public String trim ()

Returns a string that removes leading and trailing spaces


(+) public string[] Split (String regex)

Splits a string by the specified regular expression, returning the split result as an array of strings


3.StringBuffer:

StringBuffer represents a variable sequence of characters.

How it works: pre-apply a piece of memory, storing the character sequence, if the character sequence is full, will re-change the size of the buffer to accommodate more character sequences. is a mutable object, which is the biggest difference from the string (if the string object is continuously manipulated, it produces a lot of "garbage" and "disconnects-joins" frequently.) )


4.StringBuilder class:

The StringBuilder and StringBuffer functions are almost the same, except that StringBuilder is thread insecure and stringbuffer is thread-safe.


Six. Inner class

Definition: Defines another class within the class. If you define a class inner inside a class outer, inner is called an inner class, and outer is called an external class.

public class Outer {private String name= "China";   public void func (int x) {public class localinner{public void Method () {System.out.println ("Intra-domain class accesses the attributes of the outer classes:" +name);   System.out.println ("Local class access includes parameters of its methods" +x); }   }   }}

The benefits of using an inner class: (1) You can easily access the private properties of an external class. (2) reduces the size of the bytecode file generated after the class file is compiled.

Disadvantage: The structure of the program is unclear.

    1. member Inner class: (1) The static variable cannot be defined.

      (2) Holding references to external classes.

(3) Format (external instantiation member inner Class): outer class. Inner class Inner Class object = External class instance. New inner Class ();

public class Outer {private String name= "Chinese";   member Inner class memberinner{public void Method () {System.out.println ("inner class can access private properties of external class:" +name);   }} public Memberinner getmemberinstance () {return new Memberinner (); }}


2. Static inner class: If an inner class uses a static declaration, this inner class is called a static inner class, which is actually equivalent to an external class.

                            can be accessed through an external class. Inner class. The V static inner class does not hold a reference to an external class and can be created without creating an external class object v static inner class can access external static variables if access to external class non-static                              member variables must be accessed by an instance of an external class to externally instantiate a static inner class object in the format: outer class inner class   inner class object outer class inner class ();

public class Outer {private String name= "China";      private static int population=14;   Static class Staticinner{public void Method () {System.out.println ("Static inner class accesses the static property of the outer class directly:" +population);   Outer out=new Outer ();   SYSTEM.OUT.PRINTLN ("Accessing a non-static property through an external class object in a static inner class:" +out.name);   }} public static Staticinner Getstaticinner () {return new Staticinner (); }}


3. Local inner class: the Intra-domain class is an inline class defined in a method, so the scope of the class is limited to that method, and the object generated by the class can only be used in that method. A local class cannot contain static members.

public class Outer {private String name= "China";   public void Func (Int. x) {class localinner{public void Method () {System.out.println ("Intra-domain class accesses the attributes of the outer classes:" +name);   System.out.println ("Local class access includes parameters of its methods" +x);   }} new Localinner (). method (); Instantiate a local class object in a method within a local class, and invoke its method}}


4. Anonymous inner class: If an inner class is used only once throughout the operation, it can be defined as an anonymous inner class.

An inner class without a name this is a mechanism that Java is designed to facilitate our programming, because sometimes an internal class needs to create an object of its own, and it will not be used in the future, and it would be appropriate to use an anonymous inner class.

public class Testanonumity {public static void main (string[] args) {jumping j=new jumping () {@Overridepublic void jump () {S Ystem.out.println ("Jump ...");}; J.jump ();}}











Java Small white Dry Shop (iv)

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.