To elaborate on classes in Java

Source: Internet
Author: User
Objective

Recently in the study of "Java Programming ideas" learned the internal class

Class is not the kind of everyday use can also tell the flowers are not ...

In fact, in Java, the types of classes and the use of a variety of different patterns. Among them are mainly

General class

Inner class (nested Class)

Anonymous class

Abstract class

Static class

Sealing class

Let's talk about this a lot first. Next, we will start with the application scenario, the definition, the instantiation, these 3 aspects, and learn the basic knowledge about the class.

General-Class application scenarios

The origin of the class is rooted in the feather of flock together. The same characteristics and behavior extraction (attributes and methods) of the world, summarized into a type. is the most common and basic unit of our programming world.

Defined

 Public class Cat { public Cat (String _color) {    this. color=_color;}  // Properties  Public  // Method (behavior)publicvoid  run () {System.out.println (color + "The cat is coming to you gracefully");}} C.run ();

This is how the most basic classes are used.

Inner class
Application Scenarios
Inner classes are also called nested classes.
Can be subdivided into non-static inner classes, static inner classes,
It is used in a wide variety of scenarios and
Defined

Non-static inner class
 Public classInnerclasstest {PrivateString name;  Publicinnerclasstest (String name) { This. name=name; }   Public class Inner{ PublicString GetName () {returnname; }    }     PublicInner Getinnerclass () {return NewInner (); }}

You can see the portion of my color change. It is defined in a normal class (external Class), it also has its own properties and methods, it can access the member variables of the external class, in addition, in order to facilitate, generally in the external definition of a method, to provide references externally, can also be used internally

Instantiation of
1         Innerclasstest innerclasstest=New innerclasstest ("Zhang San"); 2         Innerclasstest.inner Inner=innerclasstest. New Inner (); 3         System.out.println (Inner.getname ()); 4         Innerclasstest.inner s= innerclasstest.getinnerclass (); 5         System.out.println (S.getname ());

As you can see, if you need to access the inner class, you first need to have a reference to the parent class. That is, the outer class instantiation of the first row
Lines 2nd and 4th show 2 ways to instantiate non-static inner classes. One is. New inner class another is to get an object by calling a method in an external class


Static Inner class
Application Scenarios
Static internal class usage is relatively uncommon, see Builder mode
Defined
1  Public  classInnerclasstest {2     Private StaticString name;3      Publicinnerclasstest (String name) {4Name=name;5     }6 7     Public Staticclassinner{8         public Static String GetName () {9             returnname;Ten         } One     } A      PublicInner Getinnerclass () { -         return Newinner (); -     } the}

Instantiation of
It is important to note that the inner class itself is static if it is to set the method to a static method.
String name= InnerClassTest.Inner.getName ();
Because it is a static class, it does not require an instance of the class, the direct external classes point out the line, but because the external class name is not assigned, so print out name is null
Anonymous class
Anonymous classes are known as anonymous inner classes and are also consistent with internal classes
Usage Scenarios
The reason for it to be said alone is that there are very many scenarios. Simplify the code, for only one or two small methods of interface, do not have to create an interface file, elegant a lot of first to raise a chestnut

Defined
        New DataTemplate (). Exectue (new   Idatamanager() {            @Override            publicvoid  Process () {                System.out.println ("Implementation of the interface implementation Method");            }        });

As can be seen from the discoloration section, this is an interface, and the interface is normally not new. In the class can be used arbitrarily, as long as the implementation of the interface method can be.

This way of use, everywhere

New TimerTask () {           @Override           publicvoid  run () {                          }       }
   New Runnable () {           @Override           publicvoid  run () {                          }       };

is not very familiar, do asynchronous tasks, scheduled tasks commonly used to.

    New Comparator () {            @Override            publicint  Compare (Object O1, Object O2) {                 return 0;            }            @Override            Publicboolean  equals (Object obj) {                return false ;            }        };

is not more familiar with, do a sort of comparison when often used. In Java, anonymous classes are everywhere.

This shorthand method is equivalent to

 Public class Implements Comparator {    @Override    publicint  Compare (Object O1, Object O2) {         return 0;}    }
Abstract class
Abstract class As the name implies, the common characteristics of abstraction, extraction of common behavior, subclass to achieve. Keyword abstract   
Add abstract to a class it can have no abstract method. Conversely, if an abstract modifies a method in a class, it is called an abstract class, and the class must be given an abstract adornment
Usage Scenarios
Abstraction is an important concept in object-oriented software engineering, and abstract classes and interfaces are similar and can be overridden by subclasses. The difference is that the interface has no method body, and the abstract class can have the property and method body normally, and can have its own common method.
For example, the next single binding card, card class is an abstract class, sub-categories have bank cards, credit cards, membership cards, points card, supermarket joint card. They all have common attributes, such as card number, type, and common payment behavior.
Common with abstract factories, belong to the most common design patterns, the next single business logic will also see the abstract figure. Different types of orders perform different sub-class logic (e.g., regular orders, treasure-taking, patchwork, gift-giving)
Defined
 Public Abstract class Implements Comparator {    @Override    publicint  Compare (Object O1, Object O2) {         return 0;}    }

This abstract class can inherit an interface, it can not need an abstract method, but the abstract class cannot be instantiated, because it is not an image, it requires subclass inheritance

 Public class extends nimingtest {}

Instantiation of
New Abstractchildclasstest (). compare ();

At this point, you can access all of the public methods of the parent class, and if the parent class has an abstract method, the subclass must implement this method, unless the same is an abstract class.

At this point, add an abstract method to the abstract class, let the subclass inherit

 Public Abstract class Implements Comparator {    @Override    publicint  Compare (Object O1, Object O2) {         return 0;    }      Public Abstract   String getName ();}

Sub-class

 Public class extends nimingtest {    @Override    public  String getName () {        returnnull ;    }}

Use

     New Abstractchildclasstest (). Compare ();      New Abstractchildclasstest (). GetName ();

Can also bypass the like, write their own anonymous class, dealing with an interface can also be used for abstract class

New nimingtest () {            @Override            public  String getName () {                return "";            }        };

It can be seen that the abstract class, which cannot be new before, can actually skip the inherited environment and implement the abstract method directly in an anonymous way.

When using the

    New nimingtest () {            @Override            public  String getName () {                return "XSS";            }        }. GetName ();        SYSTEM.OUT.PRINTLN (name);

Static class

Static classes are a special existence because there is only one copy of the metadata in the entire memory. So there is no possibility of instantiation, in fact, static inner class is considered static class.

Keyword static

Keywords cannot be decorated with classes (external classes only) and can only be used for member variables and methods. Any class that has a method that is modified by static, we call him static class.

Static variables, static blocks, static methods static internal classes

Usage Scenarios

Places that are typically used for tool classes or similar enumeration of member variables to compare fixed values

Defined

The following code shows static variables, static blocks, static methods, static internal classes

Public  class Staticclasstest {
static {
System.out.println ("Static block initialization work");
}
public static int count;
public static int getsum (int a,int b) {
return a+b;
}
public static Class staticinnerclass{
public void Register () {
SYSTEM.OUT.PRINTLN ("Only registered channel");
}
}
}

Instantiation of

No instantiation is required for static correlation, only one copy in memory

        (Staticclasstest.getsum);        Staticclasstest.count= 2;

Sealing class

Sealed classes are also called final classes. There is no difference between a normal class and a property. Unique attribute: cannot be inherited like this

Keyword: final

Usage Scenarios

The person who created the class felt the class and the need not to extend it, and no one could extend it, adding the class to the final decoration so that it could not be inherited

Defined
final class Innertestmain {}
Instantiation of

Just like the normal class, new is good. The sealing class is seldom seen in daily use and is not widely used

Summarize

Listed a circle down, only to find that the protagonist is the inner class.

To calculate, non-static inner class, anonymous inner class, static inner class, abstract inner class, abstract static inner class. There are also LAMDA expressions, which are also anonymous classes to use.

The knowledge about classes is here.

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.