Object-oriented Java (ii)

Source: Internet
Author: User
Tags define abstract modifiers

Key points of knowledge:

    1. Object class
    2. Single-Case mode
    3. Final keyword
    4. Abstract class
    5. Interface
    6. Inner class
    • Object class

Object All classes of the direct or indirect parent class, Java believes that all objects have some basic common content, which can be continuously extracted upward, and finally extracted to a top-level class, the class is defined by all objects have the functionality.

1.boolean equals (Object obj): Used to compare two objects for equality, in fact, the internal comparison is the address of two objects.

Depending on the object, it is different to judge whether the object is the same, so when defining the class, it is common to make the Equals method, to establish whether the object of this class is the same.

 Public Boolean equals (Object obj) {    ifinstanceof person ))         return false ;     = (person) obj;         return this. Age = = p.age;        }

2.String toString (): Turns the object into a string; The format returned by default: class name @ hash value = GetClass (). GetName () + ' @ ' +integer.tohexstring (hashcode ())

To make sense for the contents of the object's corresponding string, you can create a string representation that is unique to the class object through replication.

 Public String toString () {    return ' person: ' + age;}

3.Class getclass (): Gets the byte-code file to which any object runtime belongs. Reflect in detail when said.

4.int hashcode (): Returns the hash code value of the object, which is supported in order to improve the performance of the hash table.

    • Single-Case mode

Problem solved: Ensure that the object uniqueness of a class in memory.

For example: When multiple programs read a configuration file, it is recommended that the configuration file be encapsulated as an object. It is easy to manipulate the data, and to ensure that multiple programs read the same configuration file, it is necessary that the profile object is unique in memory.

The Runtime () method is designed as a singleton pattern.

How to ensure the uniqueness of the object?

Thought: 1. Do not allow other programs to create this class object. 2. Create an object of this class in this class. 3. Provide external methods for other programs to obtain this object.

Steps:

    1. Because constructor initialization is required for creating objects, it is not possible for other programs to create such objects as long as the constructors in this class are privatized.
    2. Creates an object of this class in a class.
    3. Defines a method that returns the object so that other programs can obtain the object by way of the method. (Effect: controllable)

The code reflects:

    1. Privatization constructors
    2. Creates a private and static object of this class.
    3. Defines a public and static method that returns the object.
//a hungry man typeclasssingle{PrivateSingle () {}//privatisation constructor.     Private StaticSingle S =NewSingle ();//creates a private and static object of this class.      Public StaticSingle getinstance () {//defines a public and static method that returns the object.         returns; }}//Lazy Type: Lazy loading mode. classsingle2{PrivateSingle2 () {}Private StaticSingle2 s =NULL;  Public StaticSingle2 getinstance () {f (S==NULL) s=NewSingle2 (); returns; }}    

    • Final keyword
    1. Final can modify class method variables.
    2. The final class cannot be inherited, but other classes can be inherited.
    3. The final modification method cannot be replicated, but it can be replicated by the parent class method.
    4. Final-modified variables are called constants, and they can only be assigned once.
    5. When the inner class is local, only the final modified variable can be accessed.
    6. The final decorated reference type variable, which indicates that the reference to the variable cannot be changed, not the value of the variable.
    • Abstract class

When describing things, there is not enough information to describe things, then the corresponding class of the description is an abstract class.

Dog:
     behavior: Scream
Wolf:
     behavior: Roar
Wolves and dogs have a common function, can be extracted,
they are one of the canine branches. The Roar is the basic function of the canine family.

 abstract  class   canine { static  abstract  void   Roar ();}  class  dog extends   canine { void      Roar () {System.out.println ( "Bark"  class  Wolf extends   canine { void   Roar () {System.out.printl    N ( "whining" ); }}

When we write a class, we tend to define methods for the class that describe how the class behaves, and these methods have a concrete method body. However, sometimes the parent knows only what kind of method the subclass should contain, but it doesn't know exactly how the subclass implements the method. The abstract class is used at this time.

Features of abstract classes:

1. Abstract methods can only be defined in abstract classes, abstract classes and abstract methods must be decorated with the abstract keyword (can describe classes and methods, can not describe variables)

2. Abstract methods can only define method declarations and do not define method implementations.

3. Abstract classes can not be created objects. (instantiated).

4. The subclass can be instantiated only if the subclass inherits the abstract class and overrides all abstract methods in the abstract class, otherwise the subclass is an abstract class.

The details in the abstract class:

1. Are there any constructors in the abstract class? There, used to initialize the subclass object.

2. Is it possible to define non-abstract methods in an abstract class?

Yes, abstract classes and general classes are not much different, are in the description of things, but the abstract class in describing things, some functions are not specific, so the abstract class and the general class in the definition, it is necessary to define properties and behavior, but, than the general class more than an abstract function, and less than the general class of a created object part.

3. Abstract and what can not coexist? Final,static,private.

4. Can you not define abstract methods in an abstract class? Yes, the purpose of the abstract method is simply to not allow the class to create objects.

5. What are the similarities and differences between general classes and abstract classes?

The same: both the general class and the abstract class are used to describe things, which can define properties and behaviors, as well as constructors.

Differences: Abstract functions cannot be defined in a generic class, and abstract classes can. A generic class can instantiate an abstract class.

A generic class can be inherited or not inherited, and an abstract class must be inherited, requiring its subclasses to overwrite all of the abstract method subclasses before it can be instantiated.

Abstract method:

When analyzing things, discovering the common content, there will be an upward extraction, there would be such a special situation, is the same function declaration, but the functional body is different

This can also be extracted, but only the method declaration is extracted, and the method body is not extracted, then this method is an abstract method.

Abstract classperson{Abstract voidShow (); Abstract voidinof (); voidturn () {}}classNewpextendsperson{@OverridevoidShow () {} @Overridevoidinof () {}//If you don't write, you'll get an error.} Public classDemo { Public Static voidMain (string[] args) {//new Person (); Error! Because abstract classes are not instantiated    }}

Abstract class Embodiment-template mode:

Solve the problem: when the internal part of the implementation of the realization of certain, part of the implementation is uncertain, then you can put the uncertainty of the partial exposure, so that the sub-class to achieve.

Abstract classgettime{ PublicLFinal voidGetTime () {//This feature can be specified with L final if no replication is required        LongStart =System.currenttimemillis ();  Code (); //an indeterminate part of the function, extracted, implemented by an abstract method        LongEnd =System.currenttimemillis (); System.out.println ("Milliseconds is:" + (end-start)); }     Public Abstract voidCode ();//abstract and uncertain functions, so that sub-class replication implementation}classSubdemoextendsgettime{ Public voidCode () {//sub-class replication function method         for(inty=0; y<1000; y++) {System.out.println ("Y"); }    }}                

    • Interface

Introduction: Abstract class is a template abstracted from multiple classes, to make this abstraction more thorough, you have to use a special "abstract class"---"Interface

An interface defines only the specifications that a class should follow, but does not care about the internal data of these classes and the implementation details within its methods.

The interface only prescribes the methods that must be provided in these classes, thus separating the specification and implementation, enhancing the scalability of the system and the maintainable line.

Example:

1. Defined with the keyword interface.

2. The members that are included in the interface, the most common are global constants, abstract methods,

Note: The members of the interface have fixed modifiers.

Member variable: public static final

Member Method: Public abstract

Interface   inter{    publicstaticfinalint x = 3; //public static final can be omitted       Public Abstract void   Show (); //public abstract can be omitted }

3. The interface has an abstract method, which indicates that the interface can not be instantiated, the subclass of the interface must implement all the abstract methods of the interface, the subclass can be instantiated, otherwise, the subclass is an abstract class.

4. There is an inheritance relationship between classes and classes, and an implementation relationship exists between classes and interfaces.

5. Interfaces and classes are different, that is, the interface can be implemented more, this is the result of multiple inheritance improvement, Java will be a multi-inheritance mechanism through a multi-implementation to reflect.

6. While inheriting another class, one class can implement multiple interfaces, so the interface avoids the limitations of single inheritance. You can also extend the functionality of a class.

7. In fact, there are many inheritance in Java, interface and interface between the inheritance of the relationship, the interface can be multiple inheritance.

Features of the interface design:

1. Interfaces are rules that are provided externally.

2. Interface is the extension of the function

3. The appearance of the interface reduces the coupling.

Abstract classes and Interfaces:

Abstract class: Generally used to describe a system unit, a set of common content to extract, you can define abstract content in the class to allow subclasses to implement, you can also define non-abstract content for the subclass to use directly, it is the basic content of the system.

Interfaces: Generally used to define the extended functionality of an object, it is necessary to have some of the features of this object beyond inheritance.

The generality of abstract classes and interfaces: they are the result of continuous upward extraction.

The difference between an abstract class and an interface:

1. Abstract classes can only be inherited, and can only be inherited. Interfaces need to be implemented and can be implemented more.

2. Non-abstract methods can be defined in an abstract class, and subclasses can be used directly.

There are abstract methods in the interface, and subclasses are required to implement them.

3. Abstract classes Use the relationship of is a.

The interface uses a relationship like a.

4. The member modifiers of the abstract class can be customized.

The member modifiers in the interface are fixed and all are public.

    • Inner class

A class is used to describe something, and if there is something specific in the thing, and the inner thing is accessing the content of the object, then this inner thing also needs to be described by class, and this class is the inner class.

If Class A requires direct access to the members in Class B, then Class B needs to establish an object of Class A. At this point, in order to facilitate the design and access, the Class A is directly defined in class B, the class A becomes the inner class. An inner class can directly access members in an external class. For external classes that want to access internal classes, you must create an object of the inner class.

Features: An inner class can access members directly from an external class, and an external class must create an object to access the members of the inner class.

1 classOuter2 {3     intnum = 4;4     //Inner class. 5     classInner6     {7         voidmethod ()8         {9System.out.println ("Method run.." +outer. This. Num);Ten         } One     } A      Public voidShow () -     { -Inner in =NewInner (); the In.method (); -     } - } -      +  - classInnerclassdemo + { A      Public Static voidMain (string[] args) at     { -         NewOuter (). Show (); -     } -}

You can use some member modifiers to decorate the private,static when the inner class is defined on the member location of the outer class.

1. Default modifier.

Direct access to the inner class's format: external class name. Internal class Name Variable name = External Class object. Inner class object;

New W Outer. New  Inner (); // This form is seldom used

But this is a rare application because inner classes are defined internally to encapsulate, and objects that want to get inner classes are usually obtained through the methods of an external class, which controls the inner class object.

2. Private modifier

Usually the inner class is encapsulated and will be privatized, because encapsulation does not allow other programs to access directly,

3. Static modifiers

If the inner class is statically decorated, which is equivalent to an external class, access limitations occur and only static members in the outer class can be accessed.

Note: If an internal member is defined inside the inner class, then the inner class must be dead static.

The internal class is compiled with the file name: External class name $ internal class name. java

Why does an inner class have direct access to members in an external class?

That's because the inner class holds a reference to an external class, which is the external class name. This

An inner class can be defined on a member location in an external class, or in a local location on an external class.

  When an inner class is defined at a local location, only the locally-modified local variables can be accessed

Anonymous inner class

  All anonymous is abbreviated form, the definition of anonymous internal classes must have a premise.

Premise: Internal classes need to inherit or implement an external class or interface, then the form of anonymous internal classes can be Ctrip.

An anonymous inner class is actually an anonymous subclass object that has a member defined internally by the end of the {}.

Anonymous inner class format: New parent class name & Interface name () {defines a subclass member or overrides a parent class method}.

Usage scenarios for anonymous inner classes:

When a function's argument is a reference to an interface type, if the method in the interface does not exceed 3. The passing of parameters can be accomplished through anonymous inner classes.

In fact, when you create an anonymous inner class, the encapsulation method in the class is not too much, preferably two or two or less.

Object-oriented Java (ii)

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.