Java basics notes -5-Java language modifiers

Java basics notes -5-Java language modifiers

5 Java language modifiers

Table top level class in the class is limited and does not include an internal class. It refers to a class defined in the interior of the class or class method.

Modifiers class Member method Construction method Member variables Local variables
abstract Y Y - - -
static - Y - Y -
pubic Y Y Y Y -
protected - Y Y Y -
private - Y Y Y -
final Y Y - Y Y

As can be seen from the table: a modified top-level class of modifiers comprises: abstract, public, final, and static, protected, private top-level class can not be modified. Member methods and member variables can have a variety of modifiers, and local variables can only be used to modify the final.

1 access control modifiers

One basic idea of ​​object-oriented implementation details, and the package is exposed interface. java language uses access control to control the character classes, and methods of the class and access privileges, thereby exposing only the interface to the user, but hide the implementation details are four levels of access control:

  • Visibility: with public modification, open to the public
  • Protected level: with protected modification, subclasses and open to the same classes in the package
  • The default level: no access control modifiers, open to the same classes in the package
  • Private Level: Private with modified, only the class itself can access, not open to the public
Access level Access control modifiers similar The same package Subclass Different packages
public public Y Y Y Y
protected protected Y - Y -
default no Y Y - -
private Private Y - - -

Member variables, methods and constructors members can be in one of the four levels of access: public, protected, default or private. Top-level class can only be in public or default access level, so the top-level class can not be modified by private and protected, the following code will result in a compile error:

private class Sample{...};

2 abstract modifier

If you move from bottom to top in the inheritance hierarchy of class, located in the upper class more versatile, even more abstract. From one perspective, a more common ancestor class, people only use it as a base class for other classes derived, rather than as a specific instance of the class you want to use. For example, consider an extension to the Employee class hierarchy. An employee is a person, a student is a person. The following classes Person and Student classes added to the hierarchy of classes.

Why spend efforts on such a high level of abstraction it? Everyone has some, such as the names of such property. Students and employees have a name attribute, so it can be placed in the general method getName superclass located on the upper level of inheritance.

Now, add a getDescription method, which returns a short description of a person. E.g:

an employee with a salary of $50,000.00
a student majoring in computer science

Implementation of this method in the Employee class and the Student class is easy. But what the Person class should provide it? In addition to the name, Person class ignorant. Of course, you can make Person.getDescription()returns an empty string. However, there is a better way is to use the abstract keyword, so you do not need to fully implement this method has.

public abstract String getDescription();
// no implementation required

In order to improve the clarity of the program, the method comprising one or more abstract class itself must be declared abstract.

public abstract class Person {
    public abstract String getDescription();
}

In addition to the abstract method of the abstract and concrete class also specific data may comprise method. For example, Person class also holds the names and specific methods return a name.

public abstract class Person {
    private String name;
    public Person(String name) {
        this.name = name;
    }
    public abstract String getDescription();
        public String getName() {
            return name;
    }
}

Abstract methods as the role of occupying their specific implementation in the subclass. Extend the abstract class can have two options. One is partially defined in an abstract class abstract class does not define a method or methods abstract class, so that it must be also labeled subclass of abstract class; the other is to define all the abstract methods, this way, it is not an abstract subclass of the.

For example, Student is defined by extending the abstract class Person class, and implements getDescription method. Since no longer contains the abstract class Student method, it is not necessary to the abstract class declaration.

Even excluding the abstract class method, the class may be declared as an abstract class.

An abstract class can not be instantiated. That is, if a class is declared as abstract, you can not create objects of this class. For example, the expression

new Person("Vinee Vu")

It is wrong, but you can create a specific sub-class of objects.

Note that you can define an object variable is an abstract class, but it can only refer to objects non-abstract subclass. E.g,

Person p = new Student("Vinee Vu", "Economics");

where p is an abstract class variables Person, Person a reference example non-abstract subclasses Student's

abstract modifier used to modify a member of the class and method;

  • Modified with abstract class represents an abstract class, abstract class abstraction layer located inheritance tree, abstract class can not be instantiated, not only create an instance of an abstract class itself is not allowed.
  • Represented by abstract modification method abstract methods, abstract method is not a method thereof, an abstract method to describe what the system function, but does not provide specific implementation, with no particular method is called abstract modification method, a method having the specific method thereof.

abstract abstract classes and methods

Modified by the keyword abstract class called abstract class (abstract class)

Such as:

abstract class A {
}

Use keywords abstract modification method called abstract method (abstract method), for example,

abstract int min(int x,int y);

For abstract method declarations only, it does not allow implementation (no method thereof), and does not allow the use of a modified simultaneously abstract and final methods and classes.

Use the abstract modifier required to comply with the following syntax rules

1. An abstract class can not abstract methods, but the method comprising abstract class must be defined as an abstract class. If the child does not have all the class of the parent class abstract method is implemented, then the subclass must also be defined as an abstract class, otherwise the compiler will go wrong.

2. No abstract static methods, static and abstract keyword can not be used together.

There may be a non-abstract constructors 3. abstract class, create an instance of a subclass may call these constructors. An abstract class can not be instantiated, but you can create a reference variable whose type is an abstract class, and let him refer to an instance of non-abstract subclass.

4. Abstract classes and abstract methods can not be final modifier modified, abstract modifier modifier can not be used in conjunction with the final, because an abstract class allows the creation of a subclass, his abstract method to be implemented, and only to his specific subclass It is instantiated, while a final modification classes have subclasses allowed, the method does not allow a final modification method subclasses cover, so both in conjunction, will be self-contradictory.

An important feature of an abstract class is not allowed to instantiate, such as apple bananas are concrete classes, abstract classes and fruits are the same. Examples of fruit itself does not exist in nature, examples of which exist only concrete subclasses:

Fruit fruit=new Apple();

Inheritance tree, you can always handle the object class is regarded as an object of the parent class. When the parent class is a concrete class object's parent class object included parent class itself, and the object of all the specific subclasses; when the parent class is an abstract class, object parent class object included all concrete subclasses, therefore, a so-called abstract class can not be instantiated, it is an abstract class that can not create an instance of itself, however, can create an apple object and see it as a fruit objects.

The abstract method can not be modified private modifier, it is as if the method is abstract, represents the parent class only affirm with a certain function, but does not provide an implementation, this approach needs to be a subclass to achieve it, the parent class the abstract methods must make a subclass is visible. Otherwise, the statement never achieve a method in the parent class is meaningless, if the parent class java allows simultaneous use abstract and private modification, it means never achieve declare a method in the parent class, so this situation is not allowed in java.

Note: abstract class can no abstract methods.

If an abstract class is a subclass of abstract class that can override the abstract methods of the parent class, you can inherit the abstract method.

Abstract subclass of abstract class, if not, then it can be instantiated, which may lead to the execution of the abstract class constructor, and then perform the domain initializer for an instance variable.


3 final qualifier

final has the meaning can not be changed, it can be used to modify a non-abstract class, members of non-abstract objects, and variables.

  • It can not be inherited by final modified class, not the subclass
  • With final modification method not covered by subclasses Method
  • A constant that represents a final modification of variables can only be assigned a value

final can not be used to modify the constructor, because the "cover method" member method applies only to the concept of class, not for the class constructor, covering the relationship does not exist between the Constructor methods and subclasses of the parent class Therefore a final modification constructor is meaningless. private method for modifying the parent class does not cover the method of the subclass, and therefore private final type of process is the default type.

The method or class final main objectives are: to ensure that they do not change the semantics in a subclass. For example, Calendar class getTime setTime and methods declared as final. This indicates that the Calendar class designer responsible for conversion between the Date class and calendar status, and does not allow subclasses to deal with these issues. Similarly, String class is final class, which means allow anyone to define a subclass of String. In other words, if there is a reference to a String, it must be a reference to the String object, but can not be objects of other classes.

3.1 final class

Inheritance of weakness package was broken, subclasses access to the parent class implementation details, but also to cover the modifications of the method implementation details, in the following cases may be considered for the final type of the class definition, so that the class can not be inherited. All methods in a final class method automatically become final.

  • Not specifically designed for the inherited class, there is a complex relationship between method calls the class itself, if free to create subclasses of these classes, subclasses is likely to deliver the details wrong modify the parent class.
  • The reason is in the security, implementation details of the class does not allow any changes
  • When you create an object model, convinced that this class will not be extended

For example, JDK the java.lang.String class final class is defined as:

public final class String {
    ···
}

If another class inherits the String class, it will cause a compiler error

3.2 final method

In some cases, for security reasons, the subclass does not allow child class overrides a method, this method can now be declared as final type. For example in the class java.lang.Object, getClass () method final type, and equals () method is not a final type:

public class Object {
    public final Class getClass() {
        ...
    }
    public boolean equal(Object o) {
        ...
    }
}

All Object methods can be overridden equals () method, but it can not cover the getClass () method. Otherwise it will cause a compiler error.

3.3 final variable

With a final modified variable represents the value will not change constants.

For example, two constants defined in the class java.lang.Integer:

public static final int MAX_VALUE=2147483647;
public staric final int MIN_VALUE=-2147483647;

final variables have the following characteristics:

1.final modifier may be modified static variables, local variables and instance variables, respectively static variables, local variables and instance variables.

2. In the section initialization of member variables, member variables mentioned classes do not have to explicitly initialized, but this does not apply to final member variable. final member variable must be explicitly initialized, otherwise it will cause a compiler error.

E.g:

public class Sample {
    static final int a=1;
    static final int b;
    static {
        b=1;//合法
    }
}

3.final variables can only be assigned a value

E.g:

public class Sample {
    private final int var1=1;
    public Sample() {
        var1=2;  //错误,不允许改变实例变量的值
    }
        public void method(final int param){
        final int var2=1;
        var2+=;  //编译错误
        param++;  //编译错误,不允许改变final类型参数的值
    }
}

Examples var1 constants are the following Sample class constructor initializes both the Samlpe () and Sample (int x), which is legal. Sample because when you create an object, it will only execute a constructor, so var1 instance constants are not initialized twice:

class Sample {
    final int var1;//定义实例常量
    final int var2=0;//定义并初始化var2实例常量
    Sample() {
        var1=1;//初始var1化实例常量
    }
    Sample(int x) {
        var1=x;//初始化var1实例常量
    }
}

4. If the reference type variable modified with final, then the variable is always only refer to an object, but you can change the contents of an object, such as:

public class Sample {
    public int var;
    public Sample(int var) {
        this.var=var;
    }
    public static void main(String args[]){
        final Sample s=new Sample(1);
        s.var=2;//合法,修改引用变量s所引用的Sample对象的var属性
        s=new Sample(2);//编译出错,不能改变引用变量s所引用的Sample对象
    }
}

In a program to define the constant by the final modifier, it has the following functions:

  • Improve security code, modify the value of fixed against illegal and not allowed to change data
  • Improve the maintainability of the program code
  • Improve the readability of the program code

4 static modifier

static modifier can be used to modify a member variable of the class, members of the code blocks and methods:

  • With modified static member variables for static variables can be accessed directly through the class name.
  • With modified static member methods for static methods can be accessed directly through the class name.
  • With a static modification of program code blocks for static code block, when the Java virtual machine to load the class, it will execute the code block.

The modified static member variables and member methods are indicated owned by a class of all, it does not depend on the particular instance of the class, all instances of the class share, as long as the class is loaded, the class name at runtime based on the java virtual machine will be able to a method to locate the area of ​​the data area thereof.

4.1 static variables

Member variables, there are two, one is modified static variable called class variables or static variables, one is not modified static variable, called an instance variable.

Differences are as follows:

  • Only a static variable in memory backup runtime java virtual machine memory allocated only once as static variables, memory allocation completion of the process of loading a static variable in the class can be accessed directly through the class name static variables.

  • For instance variable, did not create an instance, it will allocate a memory for the instance variables, instance variables can have more than one backup in memory of each other.

In the inner class, you can directly access static variables in any way in other classes, you can visit it to his static variable through the class name of a class.

E.g:

public class Sample{
    public static int number;//定义一个静态变量
    public void method(){
        int x=number;//在类的内部访问number静态变量
    }
}
public class Sample{
    public void method(){
        int x=Sample.number;//通过类名来访问number静态变量
    }
}

static variables in a way similar to other languages ​​such as global variables in the C language, Java language does not support does not belong to any class of global variables, static variables provide this function, he has two effects:

  • All instances of the class can be shared, the shared data can be used as examples of interaction between
  • If all instances of the same class comprises a constant property, this property can be defined as a constant static type, saving memory space.

4.2 static method

Members of the methods are divided into static and instance methods, static methods or classes with a static method called the modified method. Static methods and static variables, without creating an instance of the class can be accessed directly through the class name, for example:

public class Sample{
    public static int add(int x,int y){//静态方法
        return x+y;
    }
    public class Sample{
    public void Sample{
    public void method(){
            int result=Sample.add(1,2);//调用Sample类的add()静态
            System.out.println("result");
        }
    }
}

Contents 1. static methods accessible

Because the static method does not require any instance that it belongs to the class will be called, so a static method can not be used this keyword can not directly access the instance variables and instance methods of their class, but the class can access the static variables belong directly and static methods.

2. Examples of ways to access the contents of

If a class is not static modification, then it is an instance method. In an example process belongs can directly access the static class variables, static methods, instance variables and instance methods.

Examples Examples of methods have been cited several times, do not cite

3. Static methods must be implemented

Static method used to represent a class-specific features, to achieve this function does not depend on the specific example of the class, does not depend on its subclasses. That being the case, the current class must provide an implementation for static methods. In other words, a static methods can not be defined as an abstract method. Definitions The following methods are illegal:

static abstract void method();//编译出错,不能连用

If a method is static, it must implement its own method; if a method is abstract, then it is only that class has the function, but does not realize it, it will be achieved in a subclass.

4. As the inlet of the main program () method is static

So that as long as the java virtual machine to load the main () method belongs to the class, you will be able to execute the main method without first creating an instance of this class.

You can not directly access the instance variables and instance methods () static method main in. For example, the following compilation error:

public class Sample{
    int x;
    void method(){
    }
    public static void main(String args[]){
        x=9;//编译错误
        this.x=9;//编译错误
        method();//编译错误
        this.method();//编译错误
    }
}

The correct approach is accessed by reference Sample instances instance methods and instance variables

public class Sample{
    int x;
    public static void main(String args[]){
        Sample s=new Sample();
        s.x=9;
        s.method();//合法
    }
}

The method bytecode method area are located

Whether it is an instance method or a static method, the byte code are located in their area square method, Java compiler translates Java source code into a method of binary coding, became byte code, the parser Java virtual machine is able to resolve this species bytecode.

Note: the following two points only need to know, you do not need to master

4.3 static block

Class can contain static block of code, it does not exist with any method body, the Java Virtual Machine is loaded, it will execute these static block of code, if a class contains more than one block of code, then press the Java virtual machine they appear in the class they executed the order, each static block of code is executed only once.

4.4 static introducing static

From the beginning of the introduction of the static import JDK5 grammar, its purpose is to require frequent access method or occasion a member variable of the same class, simplifying the code.

Guess you like

Origin www.cnblogs.com/whatsabc/p/11489377.html