Java language basics

Source: Internet
Author: User

Java language basics

I. Object-Oriented Programming (OOP)

What are the differences and relationships between classes and objects that are called objects of all things?

Class is a definition of a certain type, such as a string, an animal, a person, an airplane, etc. The object refers to a specific string, an animal, a person...

For example, a pig is a type. It is defined as a pig. It contains weight, age, food, sleeping, and the object is this pig, that pig, or a pig starts up with a name named "". This specific pig is an object, and the name "" is called an object reference, we can find the specified pig.

package com.yq;public class Pig {    private int height;    private int age;    void eat() {        System.out.println("eat()");    }    void sleep() {        System.out.println("sleep()");    }    public String toString() {        return getClass().getName() + "===@===" + Integer.toHexString(hashCode());    }//    public String toString() {//        return getClass().getName() + "@" + Integer.toHexString(hashCode());//    }    public static void main(String[] args) {        Pig xiaoBai = new Pig();        Pig xiaoHei = new Pig();        xiaoBai.eat();        xiaoHei.sleep();        System.out.println(xiaoBai);        System.out.println(xiaoHei);        System.out.println("xiaoBai==xiaoHei?" + (xiaoBai == xiaoHei));        System.out.println(xiaoBai.getClass());        System.out.println(xiaoHei.getClass());        System.out.println("xiaoBai.getClass()==xiaoHei.getClass()?" + (xiaoBai.getClass() == xiaoHei.getClass()));    }}
eat()sleep()com.yq.Pig===@===74a14482com.yq.Pig===@===1540e19dxiaoBai==xiaoHei?falseclass com.yq.Pigclass com.yq.PigxiaoBai.getClass()==xiaoHei.getClass()?true

About '='

For referenced variables, when compared, the two referenced variables reference the same object, that is, whether the addresses of the objects stored in the two references are the same.

For basic data types, the comparison is whether the two data types are equal.

 

It is special and interesting for the String type.

Package com. yq; public class Test {public static void main (String [] args) {// String as an object to use System. out. println ("String is used as an object"); String str = new String ("hello"); String str2 = "he" + new String ("llo"); System. out. println ("str = str2? "+ (Str = str2); System. out. println (str + "@" + str. hashCode (); System. out. println (str2 + "@" + str2.hashCode (); // use String as a basic type. // If the String buffer pool does not have a String object with the same value as the specified value, in this case, the VM creates a new String object and stores it in the String buffer pool. // If a String object with the same value as the specified value exists in the String buffer pool, the VM will directly return a reference to an existing String object instead of creating a new String object. System. out. println ("String is used as a basic type"); String s1 = "java"; String s2 = "java"; System. out. println ("s1 = s2? "+ (S1 = s2); System. out. println (s1 + "@" + s1.hashCode (); System. out. println (s2 + "@" + s2.hashCode (); System. out. println ("String mixed use"); String st1 = "hello java"; String st2 = new String ("hello java"); System. out. println ("st1 = s2? "+ (St1 = st2); System. out. println (st1 + "@" + st1.hashCode (); System. out. println (st2 + "@" + st2.hashCode ());}}
String as an object to use str = str2? Falsehello @ 99162322hello @ 99162322String as a basic type to use s1 = s2? Truejava @ 3254818java @ 3254818String mixed use st1 = s2? Falsehello java @-1605094224 hello java @-1605094224

In the output result, the hashCode is clearly equal. Why are the objects different?

public int hashCode() {        int h = hash;        if (h == 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = 31 * h + val[i];            }            hash = h;        }        return h;    }

In the above String source code, we can see that the String class uses its value as a parameter and then calculates the hashcode,
In other words, as long as the String with the same value is not an object, all hash values are equal.

In the Object superclass, hashCode () is a native local method and cannot be implemented.

Objects are stored in the heap of the memory, while basic types are stored in the stack of the memory.

 

Ii. Operators

Shift Operator <, >>, >>>

The object operated by the shift operator is a binary "bit" and can only be used to process integer types. If the char, byte, or short type value is shifted, then they will be automatically converted to the int type before the shift, and the result is also int. For long processing, the result is also long.

<: Left shift operator. The value 0 and num are supplemented at the low position <1, which is equivalent to num multiplied by 2.

>>: Right shift operator. If the symbol is positive, the value 0 is added for the high position. If the symbol is negative, the value 1 is added for the high position. num> 1 is equivalent to dividing num by 2.

>>>: Shifts right without a symbol. Ignore the symbol bit. The empty space is filled with 0.

Ternary operator exp? Value1: value2

If the exp expression is true, the value of value1 is returned. Otherwise, the value of value2 is returned. The ternary expression can be nested.

'+' Operator, which is a string operator used to connect strings.

The '() type' type conversion operator is used to force type conversion. Generally, it automatically performs upward transformation without requiring strong conversion. Only downward transformation requires strong conversion.

',' Comma operator. The only place in java that uses the comma operator is the control expression of the for loop. In the initialization and step control part of the expression, you can use a comma-separated statement, however, when initializing, the comma expression must be of the same type.

3. Process Control

If-else, while, do-while, for, foreach, switch.

If statement without {}, the default range is the next statement.

Else if is not a keyword, but an if statement is added to else.

Do-while is executed only once before the condition is determined.

For (;) has the same effect as while (true.

The foreach syntax is used for arrays and containers.

package com.yq;import java.util.ArrayList;import java.util.List;public class Test {    public static void main(String[] args) {        int[] arr = {1, 2, 3, 4, 5};        for (int i : arr)            System.out.print(i + " ");        System.out.println();        List<String> ls = new ArrayList();        ls.add("a");        ls.add("b");        ls.add("c");        ls.add("d");        ls.add("e");        for (String str : ls)            System.out.print(str + " ");    }}//out1 2 3 4 5 a b c d e

Keyword return, break, and continue.

Return ends the entire method and starts the next method.

Break ends the cycle of the current layer and starts the next cycle of the outer layer of the current layer.

Continue ends the current cycle of the current layer and starts the next cycle of the current layer.

The switch selection factor is an expression that can generate an integer. char itself is an integer.

Iv. class initialization

This keyword

1. indicates the reference of the current Class Object

2. indicates the reference to the object that calls the current method.

3. the constructor calls other constructor in the class, but it cannot be called twice and must be placed in the first line of the constructor.

Static keywords

Static methods can be called directly through the class itself. Of course, class objects can also call static methods, but static methods cannot call non-static methods or this.

For static modified class attributes, the memory only allocates an address for the first initialization of this attribute. No matter how many new objects the class has, this attribute is the same reference.

Although the address is unique, that is, the reference is unique, but the reference value can still be changed.

Final keywords

If final is applied to a method, the method cannot be overwritten when it is inherited. If it is a reference type, the reference cannot be changed, but the referenced object can be changed. If it is a basic type, the value can be assigned only once and cannot be changed.

For a class, the member attributes of this class can be not initialized, because the system will set the default values for each member attribute, the default values for String and object are null, and the value type is 0, corresponding to folat or double also has the corresponding decimal point, char is also 0, displayed as blank, boolean is false, String, object is null.

Only the class member attributes are initialized by default, and the defined attributes or variables must be initialized in the method.

Initialization order

If the constructor is not specified, the system sets a default no-argument constructor. If a constructor is specified, the system does not automatically set the default constructor no matter whether a parameter exists.

The following example details the initialization sequence of various situations:

Package com. yq; class Animal {static int level; int type; static {System. out. println ("Animal static"); level = 1; System. out. println ("Animal level:" + level) ;}{ System. out. println ("Animal"); type = 10;} Animal (int I) {System. out. println ("Animal constructor") ;}} class Pig extends Animal {static int level; int height; Eye eye = new Eye (2); static {System. out. println ("Pig static"); level = 2; System. out. println ("Pig level:" + level) ;}{ System. out. println ("Pig"); height = 20; super. level = 3;} Pig (int I) {super (I); System. out. println ("Pig constructor");} class Eye {Eye (int I) {System. out. println (I + "Eyes Only") ;}} public class Test {public static void main (String [] args) {// Test 1 Pig pg1 = new Pig (2 ); system. out. println (Animal. level); // Test 2 Pig pg2 = new Pig (2); Pig pg3 = new Pig (2); System. out. println (Animal. level); // Test 3 System. out. println (Pig. level );}}
// Test 1 Output Animal staticAnimal level: 1Pig staticPig level: 2 AnimalAnimal constructor2 eyes PigPig constructor3
// Test 2 output Animal staticAnimal level: 1Pig staticPig level: 2 AnimalAnimal constructor2 eyes PigPig constructorAnimalAnimal constructor2 eyes PigPig constructor3
// Test 3 Output Animal staticAnimal level: 1Pig staticPig level: 22

Test 1 shows that the initialization sequence is: static parent class members, static parent class code blocks, static subclass members, static subclass code blocks, parent class members, and parent class code blocks, parent class constructor, subclass Member, subclass code block, and subclass constructor.

Test 2 shows that the static domain is initialized only once.

Test 3 shows that when only static domains are called, only static domains are initialized and irrelevant to objects. Static domains are determined only by classes.

If the parent class does not have a parameter constructor, you must use super to explicitly call the parent class constructor. Otherwise, an error is returned.

Variable Parameter List

Package com. yq; public class Pig {static void test (String... args) {for (String str: args) System. out. print (str + ""); System. out. println ();} public static void main (String [] args) {test ("Xiao Ming", "Xiao Hong", "Xiao Jun", "Xiao Hua ");}} // output Xiao Hong Xiaojun Xiaohua

In fact, the variable parameter list is that the compiler automatically fills in the array.

V. Access Control Permissions

Public, protected, package access permission (no keyword, default permission), private

For a class, if a java file has a public class, the java file name must be consistent with the type, and the file can only have one public class. If the entire file does not have a public class, the java file name has no relationship with the class name.

For member attributes and methods,

Public is the maximum permission and can be accessed by any class.

Protected: inherits the access permission. It can be accessed in the inheritance class of this class, and can be accessed under the same package.

Package access permission. If no permission is specified, the package access permission is used by default. Only classes under the same package can access the package.

Private is the smallest permission modifier and can only be accessed in this class.

6. Reuse class.

Combination: place any object in the new class. This object is usually modified in private mode.

Inheritance: the parent class objects are implicitly placed in the new class.

The combination technology is usually used to use the functions of the existing class in the new class, rather than its interfaces.

Inheritance technology is usually used to maintain the form of existing classes and add new code.

In general, to determine whether to use inheritance, ask if you need to perform upward transformation from a new class like a parent class. If you need inheritance, It is necessary. Otherwise, it is more appropriate to consider the combination technology.

VII. Polymorphism

Because of the existence of polymorphism, the program has extensibility.

Package com. yq; class Animal {public void eat (String args) {System. out. println ("Animal eat ():" + args) ;}} class Pig extends Animal {public void eat (String args) {System. out. println ("Pig eat ():" + args) ;}} class Cat extends Animal {public void eat (String args) {System. out. println ("Cat eat ():" + args) ;}} public class Test {public static void action (Animal anl) {anl. eat ("apple");} public static void main (String [] args) {Pig pg = new Pig (); Cat ct = new Cat (); action (pg ); action (ct) ;}}// output Pig eat (): Apple Cat eat (): Apple

If an Animal type needs to be added to a program, you only need to define the class and inherit the Animal class. The main program does not need to make any modifications.

So why can the compiler find the corresponding subclass object so intelligently and call the method correctly?

The reason is: Method binding is also called dynamic binding.

It means binding Based on the object type at runtime, instead of pre-binding when defining the method.

In java, except the static and final methods (the private method also belongs to the final method, because the final method is implicitly stated), all other methods are post-bound.

8. abstract classes and interfaces

Classes that contain abstract methods are called abstract classes.

The interface defines the method name, parameter list, and return type of the method. It can be explicitly declared as public or not, because it is the public permission by default. In addition, the member attribute in the interface, it also has a domain. The default value is final and static.

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.