Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Object-oriented example Analysis of java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the java object-oriented example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

1. Java special effects 1. Simplicity

People want to build a system that can be programmed without esoteric professional training and in line with today's standard practices. Therefore, although C++ was found to be not very suitable, the Java was designed as close as possible to the Cellular Java to make the system easier to understand. Java removed many rarely used, difficult to understand and confusing features of C++. For now, the troubles of these features far outweigh the benefits.

Indeed, Java grammar is a "pure" version of C++ grammar. There are no header files, pointer operations (or even pointer syntax), structures, unions, operator overloading, virtual base classes, and so on. However, the designer did not try to remove all inappropriate features from C++. For example, the syntax of the switch statement does not change in Java. If you know C++, you will find that you can easily convert to Java syntax.

When Java was released, C++ was not actually the most commonly used programming language. Many developers are using VisualBasic and its drag-and-drop programming environment. These developers don't think Java is simple. It was many years before the Java development environment caught up. Today, the Java development environment is far beyond the development environment of most other programming languages.

The other aspect of simplicity is small. 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; coupled with the basic standard class library and threading support (basically a self-contained microkernel), you need to add 175KB.

At that time, it was a remarkable achievement. Of course, due to the continuous expansion, the class library has become quite large. There is now a separate Java mini version (JavaMicroEdition) with smaller class libraries, which is suitable for embedded devices.

2. Object-oriented

Object-oriented is a new programming method, or a new programming specification, whose basic idea is to use the basic concepts of object, class, inheritance, encapsulation, polymorphism and so on. The software system is constructed from the objective things (that is, objects) in the real world, and the human natural way of thinking is used as much as possible in the system construction.

3. Distributed

For users, what they face is a server that provides the services they need, but in fact these services are a distributed system composed of many servers behind them. so the distributed system looks like a supercomputer.

4. Robustness

Web's multi-platform environment has special requirements for programs because they must be executed reliably in a variety of systems. Therefore, when designing Java, giving it the ability to create robust programs is a high priority. In order to achieve reliability, Java has imposed restrictions in some key areas, thus forcing programmers to find 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 examines the code at compile time. Of course, check the code at run time anyway. Many bug that are difficult to track are often difficult to reproduce at run time, which is almost impossible in Java. Because it is one of the key features of Java to make written programs run in a predictable way under different operating conditions. To better understand how robust Java is, analyze the two main causes of program failure: memory management errors and unhandled exceptions (that is, run-time errors). In traditional programming environment, memory management is a difficult and tedious task. For example, in Candlestick +, programmers have to manually allocate and free all dynamic memory. Sometimes this can cause problems because programmers 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 fundamentally eliminate these problems by managing the allocation and release of memory for you (in fact, freeing memory is completely automatic, because Java provides garbage collection for objects that are no longer in use). Anomalies in traditional environments are usually caused by errors such as "divide by zero" or "file not found" and must be managed using structures that are both clumsy and difficult to understand. Java helps in this area by providing object-oriented exception handling. In a well-written Java program, all runtime errors can and should be managed by the program.

5. Security

Java removes powerful but dangerous pointers and replaces them with references. Because the pointer can be moved, the pointer can point to any area of memory, regardless of whether it is available or not, which is dangerous because this memory address may store important data or is occupied by other programs, and it is easy to use pointers to cross the bounds of the array.

Garbage collection mechanism: there is no need for programmers to directly control memory collection. The garbage collector automatically collects memory that is no longer in use in the background. Prevent the program from forgetting to recycle in time, resulting in memory leakage. Avoid program errors to reclaim the memory of the program core class library, causing the system to crash.

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

Cast: force can be successful only if the casting rules are met.

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

Four levels of security are provided in the runtime environment: bytecode verifier-class loader-runtime memory layout-file access restrictions.

6. Architecture neutrality

The compiler generates an architecture-neutral object file format, which is compiled code that can run on many processors as long as you have a Java runtime system. The Java compiler implements this feature by generating bytecode instructions that are independent of a particular 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.

The bytecode is structurally neutral and has nothing to do with the computer structure.

7. Portability

The biggest feature of Java language lies in its portability support, the so-called portability means that the same program can be deployed arbitrarily between different operating systems, which reduces the difficulty of development. In Java, if you want to achieve portability control, then mainly rely on JVM (Java Virtual Machine). Java virtual machine is a computer simulated by software and hardware, all programs can be executed as long as they are supported by Java virtual machine, and there will be different versions of JVM on different operating systems, so portability can be realized.

The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

8. Explanation

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

9. High performance

The just-in-time compiler can monitor which code is executed frequently and optimize it to increase speed. A more complex optimization is to eliminate function calls (that is, inline). The instant compiler knows which classes have been loaded. Based on the currently loaded set of classes, inlining can be used if a specific function will not be overridden. If necessary, you can also undo the optimization.

10. Multithreading

Refers to the fact that the program (a process) runs with more than one thread.

11. Dynamic

Java is essentially a static language, not a dynamic language. The remarkable characteristic of dynamic language is that it can change the program structure or variable type when the program is running. typical dynamic languages are Python, ruby, javascript and so on. Java is not a dynamic language, but Java is dynamic in the following aspects:

Reflection mechanism

Dynamic bytecode operation

Dynamic compilation

Execute other script code

II. Object

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

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

An object becomes a useless object when there is no reference to it. Java's garbage collector automatically scans the dynamic memory area of objects, collecting and releasing objects that are not referenced as garbage. When the system runs out of memory or calls System.gc () for garbage collection, the garbage collection thread runs synchronously with the system.

III. Category

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

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

1. Class declaration [public] [abstract | final] class className [extends superclassName] [implements interfaceNameList] {. }

Where the modifier public,abstract,final describes the properties of the class, className is the name of the class, superclassName is the name of the parent class of the class, and interfaceNameList is the list of interfaces implemented by the class.

2. Class body class className {[public | protected | private] [static] [final] [transient] [volatile] type variableName;// member variable [public | protected | private] [static] [final | abstract] [native] [synchronized] returnType methodName ([paramList]) [throws exceptionList] {statements} / / member method}

The meaning of the member variable qualifier:

Static: static variable (class variable)

Final: constant; transient: temporary variable for object archiving, for object serialization

Volatile: contribution variable for sharing of concurrent threads

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

Static: class method, which can be called directly through the class name

Abstract: abstract methods, no method body

Final: methods cannot be overridden

Native: integrate code from other languages

Synchronized: controls access to multiple concurrent threads

The method declaration includes the method name, the return type, and external parameters. The type of the parameter can be a simple data type or a compound data type (also known as a reference data type).

For simple data types, java implements value passing, and methods receive the values of parameters, but cannot change the values of those parameters. If you want to change the value of a parameter, use the 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 legitimate Java instructions. The scope of local variables declared in the body of the method is within the method. If the local variable has the same name as the member variable of the class, the member variable of the class is hidden.

To distinguish between parameters and member variables of a class, we must use this. This is used in a method to refer to the current object, whose value is the object from which the method is called. The return value must be the same as the return type, or exactly the same, or its subclass. When the return type is an interface, the return value must implement the interface.

4. Construction method

The construction method is a special method. Each class in Java has a constructor that initializes an object of that class.

The constructor has the same name as the class name and does not return any data types.

Overloading is often used for constructors.

Constructors can only be called by new operators

5. Notes

Comments in Java explain your code, and Java comments are not executed, so feel free to add comments.

When the line comments / /

Multiline comments / * /

6. Implicit and explicit parameters

(1) the explicit parameter is the parameter between the parentheses of the method name.

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

(3) Code example

Package com.nezha.javase;public class Test1107 {private int score; / * x is explicit parameter * score is implicit parameter * @ 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 you precede the implicit parameter with this, the implicit parameter is clearer.

It is recommended that you add the this operator before the implicit parameter, and the this operator represents this class.

7. The method of variable parameters

Before jdk5, each java method had a fixed number of parameters; however, the current version provides a way to use variable parameters.

Take sout, which is the longest used by everyone, as an example.

System.out.println ("Award No.:" + I)

All internal calls to println are

Public PrintStream printf (String format, Object... Args) {return format (format, args);}

Object... The parameter type is exactly the same as Object [], that is, you can use... This declaration is used to receive an array of the same type, but there is no fixed size of the array because it is a variable parameter.

The ellipsis here. Is part of the Java code that indicates that this method can accept any number of objects.

In fact, the printf method takes two parameters, a time format string and a time Object [] array, which holds all the parameters (if the parameter is a primitive type, autoboxing converts it to an object).

The compiler needs to convert each call to printf to bind parameters to an array and automatically box them if necessary.

Basic characteristics of object-oriented 1. Encapsulation

Encapsulation is to hide the internal details of the object as much as possible, to form a boundary, and to retain only limited interfaces and methods to interact with the outside world. The principle of encapsulation is that the parts outside the object can not access and manipulate the internal properties of the object at will, so as to avoid the destruction of the internal attributes of the object by the outside world.

(1) the information hiding of the members of the class can be realized by setting certain access rights to the members of the class.

Private: a member of a class that is qualified as private and can only be accessed by the class itself.

Default: members of a class without any access restrictions are in the default (default) access state and can be accessed by the class itself and by classes in the same package.

Protected: a member of a class that is qualified as protected and can be accessed by the class itself, its subclasses (including subclasses in the same package and in different packages), and all other classes in the same package.

Public: a member of a class that is qualified as public and can be accessed by all classes.

(2) the advantages of encapsulation

Good packaging can reduce coupling

The structure within the class can be modified freely

Can have more precise control over member variables

Hide information, implement details

(3) Code example

The id, name, and age properties are set to private and can only be accessed by this class, but not by other classes, thus hiding the information.

Provide set method for assignment and get method for value.

The function of this in the assignment method set is to solve the problem that explicit parameters have the same name as local variables.

Package com.nezha.javase;public class Student {/ / sets the id, name, and age properties to private, which can only be accessed by this class and cannot be accessed by other classes, thus hiding the information. 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, inheritance

The object of the subclass has all the properties and methods of the parent class, which is called the inheritance of the subclass to the parent class.

In Java, a parent class can have multiple subclasses, but a subclass can inherit only one parent class, which is called single inheritance.

Inheritance realizes the reuse of code.

All classes in Java are obtained by inheriting the java.lang.Object class directly or indirectly.

Subclasses cannot inherit member variables and methods that have access to private in the parent class.

A subclass can override the method of the parent class by naming a member variable with the same name as the parent class.

In Java, access to the members of the parent class is achieved through super, and super is used to reference the parent class of the current object. There are three ways to use super:

Access the hidden member variables of the parent class

Call the overridden method in the parent class

Call the constructor of the parent class

3. Polymorphism

The polymorphism of an object means that the properties or methods defined in the parent class can have different data types or show different behaviors after being inherited by the subclass. This makes the same property or method have different semantics in the parent class and its subclasses.

The polymorphism of Java is reflected in two aspects: static polymorphism realized by method overloading (compile-time polymorphism) and dynamic polymorphism realized by method rewriting (run-time polymorphism).

Compile-time polymorphism: in the compilation phase, which overloaded method is called, the compiler will statically determine which method to call according to the different parameters.

Run-time polymorphism: because the subclass inherits all the properties of the parent class (except private), the subclass object can be used as the parent class object. Wherever a parent object is used in a program, it can be replaced by a subclass object. An object can call a method of a subclass by referencing an instance of the subclass.

4. Heavy load

Method overloading is a means for classes to handle different data types in a uniform way.

Multiple methods can be created in a class with the same name but different parameters and different definitions. When methods are called, the specific method is determined by the different number and type of parameters passed to them.

The return type can be the same or different, and the return type cannot be used as a distinguishing criterion for overloaded functions.

5. Rewrite

The subclass rewrites the methods of the parent class. If a method in a subclass has the same method name, return type, and parameter table as its parent class, we say the method is overridden (Overriding).

For the original methods in the parent class, you can use the super keyword, which references the parent class of the current class.

The access modification permission of a subclass function cannot be lower than that of the parent class.

Five, four kinds of relations between objects 1. Dependence

A dependency indicates that one class depends on the definition of another class. For example, a person (Person) can buy a car (car) and a house (House), and the Person class depends on the definition of the Car class and the House class, because the Person class references Car and House. Unlike associations, there are no attributes of Car and House types in the Person class, and instances of Car and House are passed into the buy () method as parameters. In general, dependencies are embodied in the Java language as local variables, formal parameters of methods, or calls to static methods.

2. Association

Association relationships are joins between classes that let one class know the properties and methods of another class. The association can be two-way or one-way. In the Java language, associations are generally implemented using member variables.

3. Aggregation

Aggregation relationship is a kind of association relationship, which is a strong association relationship. Aggregation is the relationship between the whole and the individual. For example, the relationship between cars and engines, tires, and other parts is the relationship between the whole and the individual. Like association relationships, aggregation relationships are implemented through instance variables. However, the two classes involved in the association relationship are at the same level, while in the aggregation relationship, the two classes are at the unequal level, one represents the whole, the other represents the part.

4. Combination

Composition relationship is a kind of association relationship, which is stronger than aggregation relationship. It requires that the objects that represent the whole in the ordinary aggregation relationship are responsible for representing the life cycle of some objects, and the combination relationship can not be shared. The object that represents the whole is responsible for keeping part of the object and survival, and in some cases annihilates the object that represents the part. An object that represents a whole can pass an object that represents a part to another object, which is responsible for the lifecycle of that object. In other words, the object that represents the part can only have a combined relationship with one object at a time, and the latter is exclusively responsible for the life cycle. The life cycle of the part is the same as that of the whole.

Thank you for reading this article carefully. I hope the article "java object-oriented sample Analysis" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report