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.
Recommended study: "java tutorial"
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.
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.
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.
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.
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.
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.
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.
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.
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.
refers to the fact that more than one thread is generated when this program (a process) is running.
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:
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.
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.
[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.
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:
The implementation of the method also includes two parts: method declaration and method body.
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.
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.
Comments in Java are used to explain your code. , Java annotations will not be executed, so feel free to add annotations.
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; } }
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.
(1)可以通过对类的成员设置一定的访问权限,实现类中成员的信息隐藏。
(2)封装的优点
(3)代码实例
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; } }
子类的对象拥有父类的全部属性与方法,称作子类对父类的继承。
Java中通过super来实现对父类成员的访问,super用来引用当前对象的父类。super 的使用有三种情况:
对象的多态性是指在父类中定义的属性或方法被子类继承之后,可以具有不同的数据类型或表现出不同的行为。这使得同一个属性或方法在父类及其各个子类中具有不同的语义。
Java的多态性体现在两个方面:由方法重载实现的静态多态性(编译时多态)和方法重写实现的动态多态性(运行时多态)。
依赖关系表示一个类依赖于另一个类的定义。例如,一个人(Person)可以买车(car)和房子(House),Person类依赖于Car类和House类的定义,因为Person类引用了Car和House。与关联不同的是,Person类里并没有Car和House类型的属性,Car和House的实例是以参量的方式传入到buy()方法中去的。一般而言,依赖关系在Java语言中体现为局域变量、方法的形参,或者对静态方法的调用。
关联(Association)关系是类与类之间的联接,它使一个类知道另一个类的属性和方法。关联可以是双向的,也可以是单向的。在Java语言中,关联关系一般使用成员变量来实现。
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.
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!