Java Basics Summary

Source: Internet
Author: User

1 Object-oriented 1) object-oriented features which I) abstract

Abstraction is about ignoring aspects of a topic that are not related to the current goal, so that you can more fully focus on the aspects that are relevant to the current goal. Abstractions do not intend to understand all of the problems, but simply select one part of them, temporarily without some detail. Abstract includes two aspects, one is the process abstraction, the other is the data abstraction.

II) inheritance

Inheritance is a hierarchical model of a junction class and allows and encourages the reuse of classes, which provides a way to articulate commonalities. A new class of objects can be derived from existing classes, a process known as class inheritance. The new class inherits the attributes of the original class, which is called the derived class (subclass) of the original class, and the original class is called the base class of the new class (The parent Class). Derived classes can inherit methods and instance variables from their base classes, and classes can modify or add new methods to make them more suitable for special needs.

III) package

Encapsulation is the process and data is surrounded, access to data only through the defined interface. Object-oriented computing begins with this basic concept that the real world can be portrayed as a series of fully autonomous, encapsulated objects that access other objects through a protected interface.

IV) polymorphism

Polymorphism refers to allowing objects of different classes to respond to the same message. Polymorphism consists of parameterized polymorphism and inclusion polymorphism. Polymorphism language has the advantage of flexibility, abstraction, behavior sharing and code sharing, which solves the problem of application function with the same name.

2 Access control permissions

Modifier

In the same class

In the same package

In subclasses

Global

Private

Y

Default

Y

Y

Protected

Y

Y

Y

Public

Y

Y

Y

Y

3 Final keyword 1) final data

1. A never-changing compilation constant

2. A value that is initialized at run time, and you do not want it to change

Basic type data modified by the final keyword cannot be changed

References to objects that are decorated with the final keyword cannot be changed, but the object itself can be modified.

2) Final parameter

means that you cannot change the object that the parameter reference points to in the method.

3) Final method

There are two reasons to use the final method. The first reason is to lock the method in case any inherited class modifies its meaning. This is a design consideration: you want to make sure that the method behavior remains the same in inheritance and is not overwritten. The second reason is the efficiency issue, which is recommended in earlier versions of Java and is not currently recommended.

The class that is defined as final cannot be inherited. In other words, for some reason, you never need to make any changes to the design of the class, or for security reasons, you don't want it to have subclasses. All methods in the final class are implicitly specified as final, because they cannot be overwritten.

4 internal Class 1) General internal class

i) How to create an inner class--place the definition of the class inside the perimeter class:

Public class Parcel1 {

Defining Inner Classes

class Destination {

Private String label;

Destination (String whereto) {

label = Whereto;

}

String Readlabel () {

return label;

}

}

Public void ship (String dest) {

Creating an inner class object in a non-static method of a perimeter class

Destination d = new Destination (dest);

System. out. println (D.readlabel ());

}

Public Static void Main (string[] args) {

Parcel1 p = new Parcel1 ();

P.ship ("Tasmania");

}

}

When we use the inner class in the ship () method, it is no different from using the normal class. The real difference is that the name of the inner class is nested inside the Parcel1.

II) use. This and. New

If you need to generate references to external class objects, you can use the names of the external classes immediately after. this. The resulting reference automatically has the correct type, which is known and checked at compile time, so there is no runtime overhead. The sample code is as follows:

Public class Dotthis {

void F () {

System. out. println ("dotthis.f ()");

}

Public class Inner {

Public Dotthis outer () {

return Dotthis. this;

}

}

Public Inner Inner () {

return New Inner ();

}

Public Static void Main (string[] args) {

Dotthis dt = new dotthis ();

Dotthis.inner dti = Dt.inner ();

}

}

Sometimes you might want to tell some other object to create an internal object of its own. To do this, you must provide references to other external class objects in the new expression, and you need to use the. New syntax, as follows:

Public class dotnew {

Public class Inner {}

Public Static void Main (string[] args) {

Dotnew DN = new dotnew ();

Dotnew.inner dni = DN.new Inner ();

}

}

2) Local inner class

Definition: An inner class defined within a method or at any scope.

i) define an inner class within the scope of the method.

Public class Parcel5 {

Public Destination Destination (String s) {

class Pdestination implements Destination {

Private String label;

Private Pdestination (String whereto) {

label = Whereto;

}

Public String Readlabel () {

return label;

}

}

return New Pdestination (s);

}

Public Static void Main (string[] args) {

Parcel5 p = new Parcel5 ();

Destination D = p.destination ("Tasmania");

}

}

II) define the inner classes within any scope.

Public class Parcel6 {

Private void internaltracking (boolean b) {

if (b) {

class Trackingslip {

Private String ID;

Trackingslip (String s) {

ID = s;

}

String Getslip () { return ID;}

}

Trackingslip ts = new trackingslip ("slip");

String S = Ts.getslip ();

}

}

Public void Track () {internaltracking (true);}

Public Static void Main (string[] args) {

Parcel6 p = new Parcel6 ();

P.track ();

}

}

3) Anonymous Inner class

i) define an anonymous inner class by implementing an interface.

Public Interface Contents {

int value ();

}

Public class PARCEL7 {

Public Contents Contents () {

Defining anonymous Inner classes

return New Contents () {

Private int i = 11;

Public int value () { return i;}

};

}

}

The inner class implements the interface contents, but without a name, it is anonymous.

II) define an anonymous inner class by inheriting a class.

Public class Wrapping {

Private int i;

Public Wrapping (int x) {i = x;}

Public int value () { return i;}

}

Public class Parcel8 {

Public Wrapping Wrapping (int x) {

return New Wrapping (x) {

Public int value () {

return Super. Value ();

}

};

}

}

The inner class inherits from the parent class wrapping and overrides its method wrapping (), and the inner class is also anonymous.

III) referencing external class variables

If you define an anonymous inner class, and you want it to use an object that is defined externally, the compiler will require that its argument reference be final, or a compilation error will occur. Take a look at the sample code:

Public class Parcel9 {

Public Destination Destination (final String dest) {

return New Destination () {

Private String label = dest;

Public String Readlabel () { return label;}

};

}

}

IV) instance initialization of an anonymous inner class

It is not possible to have a named constructor in an anonymous inner class, but with an instance initialization, you can achieve the effect of creating a constructor for an anonymous inner class, as follows:

Public class Parcel9 {

Public Destination Destination (final String dest) {

return New Destination () {

{System. out. println ("Initialize inner Class");}

@Override

Public String Readlabel () {

return null;

}

};

}

}

But such a constructor is still limited, you cannot overload the instance initialization method, so you have only one such constructor.

Summary : Anonymous inner classes are somewhat restricted compared to formal inheritance, because anonymous inner classes can either extend classes or implement interfaces, but not both. And if you are implementing an interface, you can only implement one interface.

4) Nested classes

i) definition

You can declare an inner class as static if you do not need to have a connection between the inner class object and the perimeter class object. This is often referred to as a nested class.

A nested class means:

A) objects of the enclosing class are not required to create objects of the nested classes.

b) Non-static perimeter class objects cannot be accessed from objects in the nested class.

c) The fields and methods of the ordinary class can only be placed on the outer level of the class, so normal inner classes cannot have static data and static fields, nor can they contain nested classes. But nested classes can contain all of these things.

II) class inside the interface

Under normal circumstances, you cannot place any code inside an interface, but a nested class can be part of an interface. Any classes you put into an interface are automatically public and static. Because the class is static, it simply places the nested class inside the interface's namespace, which does not violate the rules of the interface. You can even implement its perimeter interface in an internal class, just like this:

Public Interface Classininterface {

void howdy ();

class Test implements Classininterface {

Public void Howdy () {

System. out. println ("howdy!");

}

Public Static void Main (string[] args) {

New Test (). Howdy ();

}

}

}

If you want to create some common code so that they can be shared by all the different implementations of an interface, it is convenient to use nested classes inside the interface.

III) accessing members of an external class from a multilayer nested class

5) Why do I need internal class 5 inheritance with polymorphism 1) What is the difference between overloading and rewriting 6 abstract classes and Interfaces 7 set 1) Tree Map

Internal implementation, red-black tree data structure principle

2) Hash Map

Internal implementation, hash table data structure

Problems with hash conflicts

3) Hash Set

Internal implementation and usefulness

4) ArrayList LinkedList Stack Queue

Data structure and internal implementation

5) The difference between hash map and hash table

i) hash table is based on thread-safe implementation, hash map is not.

II) hash table key and value do not allow null values, hash map key and value are allowed.

III) Hash table using Enumeration,hash map using iterator.

IV) Other different needs to view API documentation and source code

6) Set of inheritance System 7) hash and hash code 8 concurrent 1) thread five states

i) new (new state)

Creating a new thread is often done by means of new thread (R). Creating a new thread does not mean that the thread can immediately enter the execution state (even if the runnable state is not necessarily executing), but instead registers some information with the thread and waits for the start method of the thread instance to be invoked to start the thread into the runnable state.

II) Runnable (ready state)

When the Start method is called on an instance of the thread, the thread enters the runnable state, and the thread entering the runnable state does not necessarily mean that it is in execution (otherwise called running thread), which may be blocked or executing. Even if the runnable thread is in progress, it is not necessarily continuous execution until the end, it is likely to enter the interrupt state due to the time slice allocated by the operating system, while the other thread that obtains the time slice executes, and when the time slice occupied by other threads expires, will determine which thread continues (or starts) execution based on the priority of all the threads waiting to be executed, so it is not necessarily the same thread that was just preempted to resume execution.

III) run (running state)

The thread dispatcher sets the thread in the ready state to the current thread, and the thread enters the running state and starts running the code in the Run function.

IV) Blocked (blocked state)

1. A thread goes to sleep because of and executes the command sleep (delays). The thread can return to the runnable state only after the set delay delays expires.

2. A thread waits for the completion of the I/O operation to enter a blocking state. The thread can return to the runnable state only after the corresponding I/O operation has completed.

3. The thread cannot enter the runnable state and is blocked because another thread is currently locked. This thread (and other threads) can enter the runnable state only if the locked thread has conceded the lock. (Once a thread is locked, the entire system can only wait for the thread to execute before it can execute another thread.) )

4. A thread waits for a change in a condition to enter a blocking state. The thread will check that the condition is changed, and if it does change, then the thread can enter the runnable state only if the other thread sign the condition can have changed.

5. A thread is suspended because of the execution of the Suspend method, so it enters a blocking state. The runnable state can be resumed only if the thread is executed by the Resume method. The suspend and resume methods have gradually ceased to be used.

V) Dead (dead State)

A thread that is in a dead or terminated state will no longer be scheduled, and will no longer receive CPU time, its task has ended, or is no longer operational.

2) Start a thread

i) define a class that inherits the thread class and overloads the Run method with the following code:

Public class MyThread extends Thread

{

Public void Run () {

System. out. println ("Does the Business Method");

}

Public Static void Main (string[] args) {

MyThread MyThread = new MyThread ();

Mythread.start ();

}

}

II) Define a class implementation runnable interface, implement the Run method, the code is as follows:

Public class MyTask implements runnable{

Public void Run () {

System. out. println ("Does the Business Method");

}

Public Static void Main (string[] args) {

MyTask MyTask = new mytask ();

Thread thread = new thread (mytask);

Thread.Start ();

}

}

It is recommended that you use this method to turn on threads so that you do not have to inherit the thread class, and you can inherit other parent classes to make coding more flexible.

3) Create a thread pool using executor

Using executor to build a thread pool simplifies development.

4) generate the return value from the task

Implement the callable interface with the following code:

Public class Taskwithresult implements callable<string> {

@Override

Public String call () throws Exception {

return "Result";

}

Public Static void Main (string[] args) throws Interruptedexception,

executionexception {

Executorservice exec = executors. Newcachedthreadpool ();

future<string> future = Exec.submit (new Taskwithresult ());

System. out. println (Future.get ());

}

}

5) Sleep

An easy way to affect the behavior of a task is to call Sleep (), which causes the task to abort execution for a given time.

6) Priority level

The thread's priority passes the thread's importance to the scheduler. Although the order in which the CPU processes the existing thread set is indeterminate, the scheduler will prefer to have the highest priority thread execute first. However, this does not mean that a lower priority thread will not be executed (that is, priority will not cause a deadlock). A thread with a lower priority is simply a low-frequency execution. You can call set priority () to set a thread's precedence.

7) Concession

If you know that you have completed the work required during an iteration of the run () method's loop, you can give the thread scheduling mechanism a hint: your work is almost done, allowing other threads to use the CPU. This hint will be made by invoking the yield () method (though it is only a hint that there is no mechanism to ensure that it will be adopted). When yield () is called, you are also recommending that other threads with the same priority be able to run.

8) Background Thread

A background thread is a thread that provides a generic service in the background while the program is running, and this thread is not an integral part of the program. Therefore, when many non-background threads end, the program terminates and kills all the background threads in the process. Conversely, the program will not terminate as long as any non-background threads are still running. Set a thread as a background thread by calling the Setdaemon (True) method.

9) Add a program

One thread can call the join () method on another thread, and the effect is to wait for a period of time until the second thread finishes. If a thread is T.join () on another thread T, the thread will be suspended until the target thread end is restored (that is, T.isalive returns false).

10) Sync i) Synchronized

Java provides built-in support for preventing resource conflicts by providing the form of a keyword synchronized. When a task executes a code fragment protected by the Synchronized keyword, it checks to see if the lock is available, then acquires the lock, executes the code, and releases the lock.

The lock of the object

A) Synchronized method

All objects automatically contain a single lock (also known as a monitor). When any of its synchronized methods are called on an object, the object is locked, and other synchronized methods on the object are called only after the previous method call is complete and the lock is freed.

b) Synchronized synchronization control block

Sometimes you just want to prevent multiple threads from accessing part of the code inside the method at the same time instead of preventing access to the entire method. The code snippet that is separated in this way is called the critical section (Critical), which is also established using the Synchronized keyword. Here, synchronized is used to specify an object with a lock that is used to control the code within the curly braces synchronously.

Synchronized (SyncObject) {

This code can be accessed

By-one task at a time

}

Lock of Class

For each class, there is also a lock, so the synchronized static method can prevent concurrent access to the static data within the scope of the class.

II) Lock 11) Wait () and notify ()

Wait () allows you to wait for a condition to change, and change the condition beyond the control of the current method. Typically, this condition will be changed by another task. Wait () suspends the task while waiting for changes in the outside world, and the task is awakened and checked for changes only when notify () or notify all () occurs. When you call Wait (), the lock is released.

The difference between Wait () and sleep 14) memory model 9 generics 10 annotations One Java I/O system 12 garbage collection mechanism 1) Finalize method

A call that acts on a Java local function, such as the memory that is created when calling C + + code, requires that the memory deallocation function of C + + be called in Finalize () with a local method.

2) Several ways of garbage collection I) Reference counter mode

A simple but slow garbage collection technique. Each object contains a reference counter, and when a reference is connected to an object, the reference counter is incremented by 1. When the reference leaves the scope or is set to NULL, the reference count is reduced by 1. The garbage collector iterates through the list of objects and, when it finds that the reference count for an object is 0 o'clock, frees up the space it occupies. There is a flaw in this approach, and if there is a circular reference between objects, the "object should be recycled, but the reference count is not zero" scenario may occur. Locating the amount of work required for an object group that has an interactive reference is significant.

II) ways to find live objects

For any living object, it must eventually be traced back to the reference it survives in the stack or static storage. This reference chain may pass through several object hierarchies. Thus, if you start from the stack and the static store, traverse all references, you can find all the live objects, and then all the references that this object contains, and so on, until the network from which the reference to the stack or static store is rooted is all accessed.

The garbage collection techniques in this way are:

A) generational replication (copy collector)

Pauses the program's run, then copies all the surviving objects from the current heap to the other heap, all of which are garbage. When objects are copied to the new heap, they are next to each other, so the new heap is kept in a compact arrangement, and then the new space can be allocated directly.

Cons : There are two reasons for this recovery mechanism to reduce efficiency.

1. Additional memory required

You have to have two piles, and then you have to churn back and forth between the two separate heaps, so you have to maintain more space than you actually need. Some Java virtual machines deal with this problem by allocating a few large chunks of memory from the heap on demand, and replication actions occur between these chunks of memory.

2. When the program enters a stable state, it may only produce a small amount of garbage, or even no garbage, this way is wasteful.

B) Mark Sweep

From the stack and static storage, iterate through the many references to find all the surviving objects. The purge action will only begin when all marked work is complete. During the purge process, objects that are not marked are freed and no copy actions occur. So the remaining heap space is discontinuous, and the garbage collector will have to rearrange the remaining objects if it wants to have contiguous space.

The garbage collector can work in an adaptive manner, intelligently switching between "copy" and "Mark sweep" mechanisms.

What are the built-in objects for the JDBC API, Web Service, and JSP 1) JSPs (2) The life cycle of the servlet-LRU policy 18 class loading the JVM memory Model 20 cluster configuration

Java Basics Summary

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.