Home >Java >javaTutorial >Briefly talk about Java object-oriented

Briefly talk about Java object-oriented

WBOY
WBOYforward
2022-03-10 17:52:422267browse

This article brings you relevant knowledge about java, which mainly introduces Java object-oriented related issues, including the basic characteristics of object-oriented, the relationship between objects, etc. ,I hope everyone has to help.

Briefly talk about Java object-oriented

Recommended study: "java tutorial"

1. Java special effects

1. Simple Sex

People want to build a system that can be programmed without esoteric professional training and that conforms to today's standard practices. Therefore, although people find that C is not suitable, Java is designed to be as close to C as possible so that the system is easier to understand. Java eliminates many rarely used, difficult to understand, and confusing features of C. At present, these features cause far more trouble than good.

Indeed, Java syntax is a "pure" version of C syntax. There are no header files, pointer arithmetic (or even pointer syntax), structures, unions, operator overloading, virtual base classes, etc. However, the designers did not attempt to eliminate all inappropriate features in C. For example, the syntax of the switch statement has not changed in Java. If you know C you will find it easy to convert to Java syntax.

When Java was released, C was actually not the most commonly used programming language. Many developers use Visual Basic and its drag-and-drop programming environment. These developers don't find Java easy. It took many years for the Java development environment to catch up. Today, the Java development environment has evolved far beyond that of most other programming languages.

Another aspect of simplicity is smallness. One of the goals of Java is to support the development of software that can run independently on small machines. The basic interpreter and class support is only about 40KB; adding the basic standard class library and thread support (basically a self-contained microkernel) adds about 175KB.

At the time, this was an incredible achievement. Of course, due to continuous expansion, the class library is already quite large. There is now a separate Java Micro Edition (JavaMicroEdition) with a smaller class library, which is suitable for embedded devices.

2. Object-oriented

Object-oriented is an emerging programming method, or a new programming specification. Its basic idea is to use objects, Basic concepts such as classes, inheritance, encapsulation, and polymorphism are used for programming. Construct software systems based on objectively existing things (i.e. objects) in the real world, and use human natural thinking as much as possible in system construction.

3. Distributed

For users, a distributed system is just a server that provides the services that users need. In fact, these services It is a distributed system composed of many servers behind it, so the distributed system looks like a supercomputer.

4. Robustness

The multi-platform environment of the Web has special requirements for programs, because programs must execute reliably in various systems. Therefore, the ability to create robust programs was given a high priority when designing Java. In order to achieve reliability, Java imposes restrictions in some key areas, thus forcing programmers to detect errors early in program development. At the same time, programmers no longer have to worry about many of the most common problems that cause programming errors. Because Java is a strongly typed language, it checks the code at compile time. Of course, no matter what, the code is also checked at runtime. Many bugs that are difficult to track are often difficult to reproduce at runtime, which is almost impossible to occur in Java. Because making the written program run in a predictable way under different operating conditions is one of the key features of Java. To better understand how robust Java is, let's analyze the two main causes of program failure: memory management errors and unhandled exceptions (i.e., runtime errors). In traditional programming environments, memory management is a difficult and tedious task. For example, in C/C, the programmer must manually allocate and free all dynamic memory. Sometimes this can cause problems, as the programmer may forget to free previously allocated memory, or worse, try to free memory that is still in use by other parts of the program. Java can essentially eliminate these problems by managing the allocation and deallocation of memory for you (in fact, freeing memory is completely automatic, because Java provides garbage collection for objects that are no longer used). Exceptions in traditional environments are often caused by "divide by zero" or "file not found" errors, and they must be managed using structures that are both clumsy and difficult to understand. Java helps in this area by providing object-oriented exception handling capabilities. In a well-written Java program, all runtime errors can and should be managed by the program.

5. Security

Java has canceled powerful but dangerous pointers and replaced them with references. Since pointers can perform move operations, pointers can point to any memory area regardless of whether this area is available. This is dangerous because it turns out that this memory address may store important data or be occupied by other programs, and using pointers It is also easy for arrays to go out of bounds.

Garbage collection mechanism: Programmers are not required to directly control memory recycling. The garbage collector automatically reclaims unused memory in the background. Prevent the program from forgetting to recycle in time, causing memory leaks. Avoid program errors in recycling the memory of the program's core class library, causing system crashes.

Exception handling mechanism: Java exception mechanism mainly relies on the five keywords try, catch, finally, throw, and throws.

Forced type conversion: Forced conversion can only be successful if the forced conversion rules are met.

Java uses public key encryption (PKC) during the transmission of bytecode.

Provides a four-level security mechanism in the running environment: bytecode verifier - class loader - runtime memory layout - file access restrictions.

6. Architecture neutrality

The compiler generates an architecture-neutral object file format. This is a compiled code that can be used as long as there is a Java runtime system. , it can run on many processors. The Java compiler achieves this feature by generating bytecode instructions that are independent of the specific computer architecture. Well-designed bytecode can not only be easily interpreted and executed on any machine, but can also be quickly translated into local machine code.
Bytecode is structure neutral and has nothing to do with the computer structure.

7. Portability

The biggest feature of the Java language is its portability support. The so-called portability means that the same program can be used in different operating systems. It can be deployed arbitrarily at any time, which reduces the difficulty of development. If you want to achieve portability control in Java, you mainly rely on the JVM (Java Virtual Machine). The Java virtual machine is a computer simulated by software and hardware. All programs can be executed as long as they are supported by the Java virtual machine, and different versions of JVM exist on different operating systems, so that Enable portability.
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.

8. Interpretability

Some people say that Java is compiled. Because all Java code must be compiled, .java cannot be executed without compilation. Some people also say that Java is interpreted. Because Java code cannot be run directly after compilation, it is interpreted and run on the JVM, so it is interpreted.

9. High performance

The just-in-time compiler can monitor which codes are frequently executed and optimize them to increase speed. A more complex optimization is to eliminate function calls (i.e. inlining). The just-in-time compiler knows which classes have been loaded. Inlining can be used if a specific function will not be overridden based on the currently loaded set of classes. Optimizations can also be undone if necessary.

10. Multi-threading

refers to the fact that more than one thread is generated when this program (a process) is running.

11. Dynamics

Java is essentially a static language, not a dynamic language. The remarkable feature of dynamic languages ​​is that the program structure or variable type can be changed when the program is running. Typical dynamic languages ​​include Python, ruby, javascript, etc. Java is not a dynamic language, but Java has a certain degree of dynamics, which is reflected in the following aspects:

  1. Reflection mechanism;
  2. Dynamic bytecode operation;
  3. Dynamic compilation;
  4. Execute other script codes;

2. Object

The object is an entity used to describe objective things in the system, and it constitutes the system A basic unit. An object consists of a set of properties and a set of services that operate on the set of properties.

The instantiation of a class can generate objects. The life cycle of an object includes three stages: generation, use, and elimination.

When there is no reference to an object, the object becomes a useless object. Java's garbage collector automatically scans the dynamic memory area of ​​objects, collects and releases unreferenced objects as garbage. When the system runs out of memory or calls System.gc() to require garbage collection, the garbage collection thread runs synchronously with the system.

3. Class

A class is a collection of objects with the same properties and methods. It provides a unified abstract description for all objects belonging to the class, including properties and methods internally. Two main parts. In object-oriented programming languages, a class is an independent program unit. It should have a class name and include two main parts: attributes and methods.

Class implementation in Java consists of two parts: class declaration and class body.

1. Class declaration

[public][abstract|final] class className [extends superclassName] [implements interfaceNameList]{……}

Among them, the modifiers public, abstract, and final describe the attributes of the class, className is the class name, and superclassName is the parent class of the class. Name, interfaceNameList is the list of interfaces implemented by the class.

2. Class body

class className{
    [public | protected | private ] [static] [final] [transient] [volatile] type variableName;//成员变量
    [public | protected | private ] [static] [final | abstract] [native] [synchronized] returnType methodName([paramList]) [throws exceptionList]{
        statements
    }//成员方法
}

The meaning of member variable qualifier:

  • static: static variable (class variable)
  • final: constant; transient: temporary variable, used for object archiving, used for object serialization
  • volatile: contribution variable, used for sharing of concurrent threads

The implementation of the method also includes two parts: method declaration and method body.

  • static: class method, can be called directly through the class name
  • abstract: abstract method, no method body
  • final: method cannot be overridden
  • native: Integrate code from other languages ​​
  • synchronized: Control access to multiple concurrent threads

Method declaration includes method name, return type and external parameters. The type of the parameters can be a simple data type or a composite data type (also known as a reference data type).
For simple data types, Java implements value transfer. The method receives the value of the parameter, but cannot change the value of these parameters. If you want to change the value of a parameter, use a reference data type, because the reference data type passes to the method the address of the data in memory, and the operation on the data in the method can change the value of the data.

3. Method body

The method body is the implementation of the method, which includes the declaration of local variables and all legal Java instructions. The scope of local variables declared in the method body is within the method. If a local variable has the same name as a class member variable, the class member variable is hidden.

In order to distinguish parameters from class member variables, we must use this. this is used in a method to refer to the current object, and its value is the object that called the method. The return value must be consistent with the return type, or exactly the same, or a subclass thereof. When the return type is an interface, the return value must implement the interface.

4. Construction method

  • The construction method is a special method. Every class in Java has a constructor method that initializes an object of that class.
  • The constructor has the same name as the class name and does not return any data type.
  • Overloading is often used in constructors.
  • Constructor methods can only be called by the new operator

5. Comments

Comments in Java are used to explain your code. , Java annotations will not be executed, so feel free to add annotations.

  • When line comment//
  • Multi-line comment/**/

##6. Implicit parameters and explicit parameters

(1) Explicit parameters are the parameters between the brackets of the method name.

(2) The implicit parameter is the instance field of the class called in the class method. The called instance field is the implicit parameter.

(3) Code example

package com.nezha.javase;

public class Test1107 {
    private int score;

    /**
     * x为显式参数
     * score为隐式参数
     * @param x
     */
    public void addScore(int x){
        int temp = this.score + x;
        score += temp;
    }
}
    x is an explicit parameter
  • score is an implicit parameter
If in implicit Add this in front of the parameter to make the implicit parameter clearer.

It is recommended to add this operator in front of the implicit parameter. This operator represents this class.

7. Methods with variable parameters

Before jdk5, each java method had a fixed number of parameters. However, the current version provides available How to change parameters.

Take the most commonly used sout as an example.

System.out.println("获奖编号:"+i);
println internally calls

public PrintStream printf(String format, Object ... args) {
    return format(format, args);
}
Object...The parameter type is exactly the same as Object[], which means that...this declaration method can be used to receive arrays of the same type, but it is not fixed. The size of the array, as this is a variable parameter.

The ellipsis here... is part of the Java code that indicates that this method can receive any number of objects.
Actually the printf method receives two parameters, one is the format string and the other is the Object[] array, which stores all parameters (if the parameters are basic types, automatic boxing will convert them into objects).
The compiler needs to convert each call to printf to bind the parameters to an array and perform autoboxing if necessary.

4. Basic characteristics of object-oriented

1. Encapsulation

Encapsulation is to hide the internal details of the object as much as possible and form a boundary to the outside. Only limited interfaces and methods are reserved to interact with the outside world. The principle of encapsulation is to prevent parts other than the object from accessing and manipulating the object's internal properties at will, thus preventing the outside world from damaging the object's internal properties.

(1)可以通过对类的成员设置一定的访问权限,实现类中成员的信息隐藏。

  • private:类中限定为private的成员,只能被这个类本身访问。
  • default:类中不加任何访问权限限定的成员属于缺省的(default)访问状态,可以被这个类本身和同一个包中的类所访问。
  • protected:类中限定为protected的成员,可以被这个类本身、它的子类(包括同一个包中以及不同包中的子类)和同一个包中的所有其他的类访问。
  • public:类中限定为public的成员,可以被所有的类访问。

(2)封装的优点

  1. 良好的封装能够减少耦合
  2. 类内部的结构可以自由修改
  3. 可以对成员变量进行更精确的控制
  4. 隐藏信息,实现细节

(3)代码实例

  1. 将 id、name 和 age 属性设置为私有的,只能本类才能访问,其他类都访问不了,如此就对信息进行了隐藏。
  2. 提供set方法进行赋值,提供get方法进行取值。
  3. 赋值方法set中的this的作用是解决显式参数与局部变量同名的问题。
package com.nezha.javase;

public class Student {
    //将 id、name 和 age 属性设置为私有的,只能本类才能访问,其他类都访问不了,如此就对信息进行了隐藏。
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

2、继承

子类的对象拥有父类的全部属性与方法,称作子类对父类的继承。

  • Java中父类可以拥有多个子类,但是子类只能继承一个父类,称为单继承。
  • 继承实现了代码的复用。
  • Java中所有的类都是通过直接或间接地继承java.lang.Object类得到的。
  • 子类不能继承父类中访问权限为private的成员变量和方法。
  • 子类可以重写父类的方法,即命名与父类同名的成员变量。

Java中通过super来实现对父类成员的访问,super用来引用当前对象的父类。super 的使用有三种情况:

  • 访问父类被隐藏的成员变量
  • 调用父类中被重写的方法
  • 调用父类的构造函数

3、多态

对象的多态性是指在父类中定义的属性或方法被子类继承之后,可以具有不同的数据类型或表现出不同的行为。这使得同一个属性或方法在父类及其各个子类中具有不同的语义。

Java的多态性体现在两个方面:由方法重载实现的静态多态性(编译时多态)和方法重写实现的动态多态性(运行时多态)。

  • 编译时多态:在编译阶段,具体调用哪个被重载的方法,编译器会根据参数的不同来静态确定调用相应的方法。
  • 运行时多态:由于子类继承了父类所有的属性(私有的除外),所以子类对象可以作为父类对象使用。程序中凡是使用父类对象的地方,都可以用子类对象来代替。一个对象可以通过引用子类的实例来调用子类的方法。

4、重载

  • 方法重载是让类以统一的方式处理不同数据类型的手段。
  • 一个类中可以创建多个方法,它们具有相同的名字,但具有不同的参数和不同的定义。调用方法时通过传递给它们的不同参数个数和参数类型来决定具体使用哪个方法。
  • 返回值类型可以相同也可以不相同,无法以返回型别作为重载函数的区分标准。

5、重写

  • 子类对父类的方法进行重新编写。如果在子类中的方法与其父类有相同的的方法名、返回类型和参数表,我们说该方法被重写 (Overriding)。
  • 如需父类中原有的方法,可使用super关键字,该关键字引用了当前类的父类。
  • 子类函数的访问修饰权限不能低于父类的。

五、对象间的四种关系

1、依赖

依赖关系表示一个类依赖于另一个类的定义。例如,一个人(Person)可以买车(car)和房子(House),Person类依赖于Car类和House类的定义,因为Person类引用了Car和House。与关联不同的是,Person类里并没有Car和House类型的属性,Car和House的实例是以参量的方式传入到buy()方法中去的。一般而言,依赖关系在Java语言中体现为局域变量、方法的形参,或者对静态方法的调用。 

2、关联

关联(Association)关系是类与类之间的联接,它使一个类知道另一个类的属性和方法。关联可以是双向的,也可以是单向的。在Java语言中,关联关系一般使用成员变量来实现。

3. Aggregation

Aggregation (Aggregation) relationship is a type of association relationship and is a strong association relationship. Aggregation is the relationship between a whole and an individual. For example, the relationship between the automobile category and the engine category, tire category, and other parts categories is the relationship between the whole and the individual. Like association relationships, aggregation relationships are also implemented through instance variables. However, the two classes involved in the association relationship are on the same level, while in the aggregation relationship, the two classes are on unequal levels, one representing the whole and the other representing the part.

4. Combination

Composition (Composition) relationship is a type of association relationship and is a stronger relationship than aggregation relationship. It requires that the object representing the whole in an ordinary aggregation relationship is responsible for representing the life cycle of part of the object, and the combination relationship cannot be shared. The object representing the whole needs to be responsible for keeping the part object alive and in some cases annihilating the object responsible for the part. An object representing a whole can pass an object representing a part to another object, which is responsible for the life cycle of this object. In other words, the object representing the part can only be combined with one object at each moment, and the latter is exclusively responsible for the life cycle. Parts have the same life cycle as wholes.

Recommended study: "java Learning Tutorial"

The above is the detailed content of Briefly talk about Java object-oriented. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete