Personally, the so-called classes in programming are the same concept as the classes in the real world that classify objects, but they are borrowed in programming. Classes represent things that have a series of commonalities and the same operations or actions, which are abstract data types in programming. Each specific individual (in the real world) and instance variables (for programming) are objects.
A class is a representation of common features (attributes and operations) of certain objects in the real world, and an object is an instance of a class.
Class attributes: is the abbreviation of the static attributes of a class, which refers to various data contained in the class, such as variables or other class objects;
A class service: is called a member function or method.
¨
The definition form of a class in Java is as follows:
[Modifier] class class name [extends parent class] [implements interface name] { class member variable declaration class method declaration}Let's talk about each part of this in detail:
Before the class keyword, the class modifiers are generally divided into three types: access modifiers public public class, final modifier (final class specifier) and abstract modifier (abstract class specifier)
Among them, the permission modifier can only be public or default (i.e. empty, nothing, indicating that it is defined as friendly), and public means that the class can be used and accessed anywhere (as long as the program can find the location of the class), whether in the same package or in different packages. Note that this is different from C++. C++ does not have a modifier to restrict access rights to class, but rather has access rights to inheritance relationships between classes. In addition, they all have access rights to class attributes and methods. The default access permission (i.e., defined as friendly) means that it can only be referenced and accessed by classes in the same package, but cannot be accessed and referenced by classes in other packages, even if imported.
It will also be mentioned later: when the default modifier of a class attribute and method is used, it is also expressed that it can only be referenced and accessed by classes in the same package.
Multiple inheritance is not allowed in Java, which is different from C++. In order to make up for this shortcoming, Java has introduced the concept of interface.
In the definition of the above class, the class body mainly contains the specific content of the class, including the attributes of the class and the methods of the class. The properties of a class can be simple variables or instances of certain classes. If it is an instance of a class, it can be defined as follows:
[Modifier] Class name object name = new class name (parameter list);
When declaring objects and complex variables, you can not use creation during declarations, but can be created in future constructors.
The methods defined in a class usually play two roles: one is to perform various operations around the attributes of the class; the other is to perform data exchange, message delivery and other operations with other classes or objects.
The syntax for declaring methods in Java is as follows:
[Modifier] Return value type method name (parameter list) throws Exception name 1, exception name 2,…{ method body: local variable declaration; statement sequence;}Class methods, also known as member functions, are used to specify operations on class attributes and implement internal functions of classes. They are also an important window for classes to interact with the outside world.
Java programmers focus on creating user-defined types called classes. Classes are also called programmer-defined types. Each class contains data and a set of methods for manipulating data. The data part in the class is called instance variables. An instance of a user-defined type (i.e., a class) is called an object.
An object is an instance of a class. A class is an abstraction of the same type of object and a template for creating an object. Creating an object in the program will open up a space in memory, including the properties and methods of the object. Create an object using the keyword operator new.
Constructor (can be compared with C++, which is almost the same as C++)
Create your own constructor
•The name of the constructor and the name of the class are the same. When constructing an object of the Employee class, this constructor is started and the instance field is assigned an initial value. In Java, definition and initialization are unified - both are indispensable.
For example, when creating an instance of the Employee class with the following code,
newEmployee ("James Bond", 100000,1950,1,1);
The characteristics of the constructor are:
(1) The constructor and class have the same name.
(2) A class can have multiple constructors.
(3) The constructor can have 0, 1 or more parameters.
(4) The constructor has no return value.
(5) The constructor is always called with the new operator.
The role of constructor
(1) Object Initialization
(2) Introduce more flexibility (variable assignment or more complex operations)
(3) The constructor can be not defined in Java
A constructor can be not defined in Java, and the system will automatically generate a default constructor for the system. The name of this constructor is the same as the class name, it has no formal parameters and does not perform any operations.
Method Overview
A Java program is composed of class definitions, and the class has two parts: properties and methods. What is an attribute description class, and what is a method description class does. Any object has independent memory to store its properties. All objects of the class share the method stored in memory.
In other words: methods are the main component of the class. In a class, the role of a program is reflected in the method.
The method is to create a named subroutine by JAVA. A main method and several sub-methods. The main method calls other methods, and other methods can also be called to each other, and the same method can be called any time by one or more methods.
Defining another method in one method will produce a syntax error.
(1) It is best to avoid local variables "mask" instance variables. This can be done without using the identifier of the same name in a class; parameters in method calls are used to pass numeric values and references, and methods can also be called in nested and recursively.
(2) If a non-void return value type is specified in the method body, the method must include a return statement to ensure that there is a return value in any case, and the return statement cannot be followed by any expression;
The basic structure of Java programs is as follows:
Introduce Java class library; define user class 1 { define several variables or objects of class 1: define method 1 of class 1; define method 2 of class 1; … define method M1 of class 1; } define user class 2 { define several variables or objects of class 2: define method 1 of class 2; define method 2 of class 2; … define method M2 of class 2}Java introduced the concept of "access control modifier" that allows library creators to declare what can be used by client programmers and what cannot be used.
This level of access control is between the range of "maximum access" and "minimum access", including: public, "default" (no keyword), protected and private. The following list explains the meaning of access control modifiers:
Public access control character
For classes:
There is only one access controller for a class in Java: public, that is, public. A class is declared as a public class, indicating that it can be accessed and referenced by all other classes. Access and reference here refers to the class being visible and usable as a whole. Other parts of the program can create objects of this class, access member variables visible inside the class, and call its visible methods.
A class is visible to other parts of the program as a whole, and does not represent that all properties and methods in the class are also visible to other parts of the program. The former is only a necessary condition for the latter. Whether the properties and methods of the class can be accessed by all other classes depends on the access control characters of these properties and methods.
Used for in-class properties:
In-class attributes modified with public are called public attributes. If this class is a public class, it can be accessed by all other classes.
Default access control
Used for classes
If a class does not have access control characters, it means that it has the default access control characteristics. This default access control stipulates that the class can only be accessed and referenced by classes in the same package, and cannot be used by classes in other packages. This access feature is called package accessibility. By declaring the access control characters of the class, the entire program structure can be clear and rigorous, reducing the possible inter-class interference and errors.
Used for class attributes
If the properties and methods within the class are not limited by access control symbols, they also indicate that they are packet accessibility.
3 Private access control character private
Attributes or methods modified with private can only be accessed and modified by the class itself, and cannot be obtained and referenced by any other class, including subclasses of the class.
1). Private data, for example, has three instance fields, which contain data that is operated inside an instance of the Employee class.
private string name;
private double salary;
private Date hireDay;
The private keyword is used to ensure that these instance fields can only be accessed by the Employee class itself.
2).Private method When implementing the class, we make all data fields private because public data is dangerous. What is the situation with the method? Although most methods are public, private methods are also frequently used. These methods can only be separated by the same method.
In short, the private method can be selected in the following cases:
(1) Those methods that are not related to the user of the class.
(2) Those methods that are not easy to maintain if the implementation of the class is changed.
Protected access control character protected
Member variables modified with protected can be referenced by three types: the class itself, other classes in the same package as it, and subclasses of the class in other packages. The main purpose of using the protected modifier is to allow its subclasses in other packages to access specific properties of the parent class.
The protected keyword introduces us to a concept called "inheritance", which is based on existing classes and adds new members to it without affecting existing classes - we call this existing class "base class" or "base class". It can also change the behavior of existing members of that class. For inheritance from an existing class, we say that our new class "extends" the existing class
Private protected access control character private protected
Private and protected are used in sequence to form a complete access control character: private protection access control character. Member variables modified with privateprotected can be accessed and referenced by two classes, one is the class itself, and the other is all subclasses of the class, whether these subclasses are in the same package as the class or in other packages.
Compared to protected, the privateprotected modifier excludes non-subclasses within the same package from accessible scope, making member variables more proprietary to classes with explicit inheritance relationships rather than packages that are loosely grouped together.
Static modifier
static is called a static modifier, which modifies properties and methods in a class.
Using the static keyword can meet two requirements:
(1) One situation is that you only want to use a storage area to save a specific data - no matter how many objects you want to create, you even don't create objects at all; attributes modified by static are called static properties, and one of the most essential features of this type of attribute is that they are attributes of a class, not specific objects of any class. In other words, for any specific object of this class, a static property is a common storage unit. When any object of any class accesses it, it gets the same numerical value. When any object of any class modifies it, it is also doing operations on the same memory unit.
(2) Another situation is that we need a special method that is not associated with any object of this class. That is to say, even if the object is not created, a method that can be called directly by the class is needed.
An important purpose of static is to help us call that method without having to create an object.
Static constants
Static variables are rare. However, static constants are common. For example, a static constant is defined in the Math class:
public class Math
{…public static final double PI=3.1.4159265358979323846;…} A static method declares that a method is static has at least three meanings:
(1) When using this method, the class name should be used as the prefix, rather than a specific object name;
(2) Non-static methods are methods belonging to an object. When this object is created, the object's method has its own dedicated code segment in memory; while the static method belongs to the entire class, and its code segment in memory will be allocated and loaded according to the definition of the class and will not be exclusive to any object;
(3) Since the static method belongs to the entire class, it cannot manipulate and process member variables belonging to a certain object, but can only process member variables belonging to the entire class.
5 main method
The main method does not apply operations to any object. In fact, when the program starts executing, no objects exist yet. The static method is executed and the objects required by the program are constructed.
It prompts that each class can have a main method. This is a very convenient trick to unit test classes.
abstract is an abstract modifier that can be used to modify classes or methods.
Abstract Class
When a class is declared as abstract, this class is called an abstract class. The so-called abstract class is a class without concrete instance objects.
To address this problem, Java provides a mechanism called "Abstract Method". It belongs to an incomplete method, with only one declaration, and has no method body. Here is the syntax used when declaring abstract methods:
abstract void X();
Abstract Methods
As a class method modifier, abstract declares an abstract method that only has method headers but no specific method body and operation implementation.
It can be seen that the abstract method only has the declaration of the method header, and a semicolon is used to replace the definition of the method body: as for the specific implementation of the method body, it is completed by different subclasses of the current class in their respective class definitions.
It should be noted that all abstract methods must exist in abstract classes
middle.
In addition to abstract methods, abstract classes can also have concrete data and methods.
Abstract methods are very important concepts in Java programming language. You will use it in a lot of ways in the interface.
Note: Here we need to compare and memorize with the interface. The methods in the interface are all abstract methods. Of course, there are also attributes in the interface, and their specific properties will be described in detail later.
Final class, final attribute, final method and finalizer (there is no final modifier in C++)
final is the final modifier, which modifies classes, properties, and methods. In addition, the keywords of the terminal are very similar to final, and will be introduced together
Final Class
If a class is declared final, it means that it cannot derive new subclasses and cannot be inherited as a parent class. Therefore, a class cannot be declared both abstract and final.
Classes defined as final are usually some classes with special functions that are used to complete standard functions. Defining a class as final can fix its content, attributes and functions and form a stable mapping relationship with its class name, thereby ensuring that the functions implemented when referring to this class are accurate.
Final attributes
Many programming languages have their own ways to tell the compiler that a certain data is a "constant". Constants are mainly used in the following two aspects:
(1) Compilation period constant, it will never change;
(2) We do not want a value initialized during the runtime to change.
An instance field can be defined as final (cannot be changed). This field must be initialized when the object is constructed. That is, it must be ensured that the value has been set before the end of each constructor. The value of the field cannot be changed in the future
Final method
The reason for using the final method may be due to considerations for two reasons.
The first is to "lock" the method to prevent any inheritance class from changing its original meaning. When designing a program, this practice can be taken if you want the behavior of a method to remain unchanged during inheritance and cannot be overwritten or rewritten.
The second reason for adopting the final method is the efficiency of program execution
Terminator
The function of the terminator is a method executed when retrieving objects. Similar to the method that constructors are executed when creating objects.
example
protected voidfinalize(){ System.out.println(" "); }Other modifiers
volatile
If an attribute is modified by a volatile, it means that this attribute can be controlled and modified by several threads at the same time.
synchronized
Mainly used for thread synchronization
native
It means that the method is not written in Java language (it is written in C, C++ and other languages)
Some information found online: - Internal category
Simply put, internal classes are classes in classes, for example:
class A {private int i;private void m() {}class B {mm(int j) {i = j;m();}}}Here, B is the internal class of A, which is characterized by convenient access to private methods and properties in external classes. For example, here B can directly access private properties i and private methods m() in A.
The most important features of object-oriented programming are encapsulation (also called abstraction), inheritance and polymorphism. As an object-oriented programming language, Java has its own advantages in this regard:
"Inheritance is a form of software reuse, which is effective in reducing software complexity. Inheritance is also a feature of an object-oriented programming language. Languages that adopt objects but have no inheritance are object-based languages, but not object-oriented languages. This is the difference between the two."
The inheritance relationship between classes is a direct simulation of genetic relationships in the real world. It represents the intrinsic connection between classes and the sharing of attributes and operations, that is, subclasses can follow certain features of the parent class (inherited class). Of course, subclasses can also have their own independent properties and operations
Inheritance is a form of software reuse. New classes are generated by existing classes, and new attributes and behaviors are added by retaining their properties and behaviors, and modifying performance according to the requirements of the new class. If a child class inherits only from one parent class, it is called single inheritance; if a child class inherits from more than one parent class, it is called multi-inheritance. Note that Java does not support multiple inheritance, but it supports the concept of "interface". Interfaces allow Java to obtain many advantages of multiple inheritance and abandon corresponding disadvantages. Note: C++ supports multiple inheritance
Definition of inheritance relationship:
[Modifier] class subclass name extends parent class name, parent class name 2
The parent class name follows extends
The keyword is used to indicate which subclass of the current class is already there, and there is an inheritance relationship.
Define two subclasses of employee class Employee:
General Employee Category: CommonEmployee
Supervisor category: ManagerEmployee
There are two main aspects of subclass inheritance from parent class:
(1) Inheritance of attributes. For example, a company is a parent class, and a company has a name, address, manager, employee, etc., which are all structural aspects.
(2) Method inheritance. A parent class defines several operations, such as a company that needs to have projects, profits, appointment of managers, recruit employees, etc., and the subsidiary will also inherit these actions s;mp
classCommonEmployeeextends Employee//Subclass 1: { intm_ManagerNo ;//Define class attribute m_ManagerNo, representing employee boss number} classManagerEmployeeextends Employee//Subclass 2: { intm_SecretaryNo;//Define class attribute m_SecretaryNo, representing secretary number} Attribute inheritance and hiding
Although the Employee class is a parent class, it does not mean that it has more functions just because it is a parent class. On the contrary, sub-analogs have more functions than their parent classes. Because the subclass is an extension of the parent class, the attributes and methods that the parent class does not have are added (1) The subclass cannot access the private member of the parent class, but the subclass can access the public of its parent class.
(2) Protected access is a protective intermediate level between public and private access.
(3) Since the inherited parent class members are not listed in the subclass declaration, these members do exist in the subclass.
Here, we need to distinguish between inheritance, overwrite and overloading, several confusing concepts:
Only at the conceptual level of method can these three concepts be easily confused:
Method inheritance
For subclass objects, methods from the parent class can be used. Even if these methods are not clearly defined in the subclass, they are automatically inherited from the parent class.
Method coverage
Method override refers to: a method that defines a method with the same name to overwrite the parent class, which is an implementation of polymorphic technology. When the parent class method is overwritten in the child class, it is usually the child class version that calls the parent class version and does some additional work.
There are many things to note. Here, I mainly mention this and super. There is this in C++ (and the concept is similar to that in Java), but there is no super.
This represents the current object itself, and this represents a reference to the current object. It can be understood as another name of the object. This allows you to call the methods and properties of the current object.
For example: this.getName() and getName() are the same in the class.
Super represents the direct parent class object of the current object, and is the reference method overload of the parent class object of the current object.
Definition of overload: The method can be defined with the same method name but different parameter tables (the number, type, or order of parameters in the parameter table has different values), which is called method overloading.
•Overloading: Overloading occurs when multiple methods have the same name and contain different parameters. The compiler must choose which method to call. It picks out the correct method by comparing the parameter types in different method headers with the types of values used in specific method calls.
Polymorphism allows the processing of existing variables and related classes in a unified style, making it easy to add new features in the system. Here, posting the information you found online can more clearly clarify the polymorphisms and inheritance issues that need special attention in inheritance:
Polymorphisms of Java
Object-oriented programming has three characteristics, namely encapsulation, inheritance and polymorphism.
Encapsulation hides the internal implementation mechanism of the class, so that the internal structure of the class can be changed without affecting the user, while protecting the data.
Inheritance is to reuse the parent class code while preparing for the implementation of polymorphism. So what is polymorphism?
Method rewriting, overloading and dynamic connection constitute polymorphism. One of the reasons why Java introduced the concept of polymorphism is that it is different from C++ in terms of class inheritance. The latter allows multiple inheritance, which does bring it very powerful functions, but the complex inheritance relationship also brings greater trouble to C++ developers. In order to avoid risks, Java only allows single inheritance, and there is an IS-A relationship between derived classes and base classes (i.e. "cats" is a "animal"). Although doing this ensures the simplicity and clarity of the inheritance relationship, it will inevitably have great functional limitations. Therefore, Java introduced the concept of polymorphism to make up for this shortcoming. In addition, abstract classes and interfaces are also important means to solve the limitations of single inheritance regulations. At the same time, polymorphism is also the essence of object-oriented programming.
To understand polymorphism, you must first know what "upward transformation" is.
I defined a subclass Cat, which inherits the Animal class, and the latter is that the former is the parent class. I can pass
Cat c = new Cat();
Instantiating a Cat object is not difficult to understand. But when I define it like this:
Animal a = new Cat();
What does this mean?
It's simple, it means that I define an Animal type reference to a newly created object of Cat type. Since Cat is inherited from its parent class Animal, a reference to an Animal type can point to an object of a Cat type. So what's the point of doing this? Because subclasses are an improvement and extension to the parent class, subclasses are generally more powerful than parent classes in function, and their attributes are more unique than parent classes.
Defining a reference to a parent class type points to an object that is subclassed can not only use the powerful functions of the subclass, but also extract the commonalities of the parent class.
Therefore, a reference to the parent class type can call all properties and methods defined in the parent class, and it is helpless for methods defined in the child class but not in the parent class;
At the same time, a method in the parent class can only be called by a reference to the parent class type if it is defined in the parent class but not overridden in the child class;
For methods defined in the parent class, if the method is rewritten in the child class, the reference to the parent class type will call this method in the child class, which is a dynamic connection.
Look at the following program:
class Father{ public void func1(){ func2(); } //This is the func2() method in the parent class, because the method is overridden in the subclass below //So when called in the reference of the parent class type, this method will no longer be valid //Replace the func2() method overridden in the subclass public void func2(){ System.out.println("AAA"); } } class Child extends Father{ //func1(int i) is an overload of the func1() method // Since this method is not defined in the parent class, it cannot be called by the reference of the parent class type //So in the main method below child.func1(68) is wrong public void func1(int i){ System.out.println("BBB"); } //func2() rewrites the func2() method in the parent class Father//If the func2() method is called in the reference to the parent class type, it must be the method rewritten in the subclass public void func2(){ System.out.println("CCC"); } } public class PolymorphismTest { public static void main(String[] args) { Father child = new Child(); child.func1();//What will the print result be? } }The above program is a very typical example of polymorphism. The child class Child inherits the parent class Father, overloads the parent class func1() method, and overwrites the parent class func2() method. The overloaded func1(int i) and func1() are no longer the same method. Since there is no func1(int i) in the parent class, the reference child of the parent class type cannot call the func1(int i) method. If the subclass overrides the func2() method, then the reference child of the parent class type will call the rewritten func2() in the subclass when calling the method.
So what results will the program print?
Obviously, it should be "CCC".
For polymorphism, it can be summarized as:
(1) Use references of the parent class type to point to the object of the subclass (actual object);
(2) This reference can only call methods and variables defined in the parent class;
(3) If a method in the parent class is rewritten in the subclass, then when calling this method, the method in the subclass will be called; (dynamic connection, dynamic call)
(4) Variables cannot be rewritten (overridden). The concept of "rewrite" is only for methods. If the variables in the parent class are "rewrite" in the subclass, an error will be reported during compilation.
Polymorphism is through:
(1) The interface and implement the interface and overwrite several different classes that cover the same method in the interface (2) The parent class and the parent class and the parent class and overwrite several different subclasses that cover the same method in the parent class.
1. Basic concepts
Polymorphism: Send a message to an object and let the object decide which behavior to respond to.
Dynamic method calls are implemented by assigning subclass object references to superclass object reference variables.
This mechanism of ava follows a principle: when a superclass object refers to a variable to refer to a subclass object, the type of the referenced object rather than the type of the referenced variable determines whose member method is called, but the called method must be defined in the superclass, that is, the method covered by the subclass.
(1) If a is a reference to class A, then a can point to an instance of class A, or to a subclass of class A.
(2) If a is a reference to interface A, then a must point to an instance of a class that implements interface A.
Java polymorphism implementation mechanism
SUN's current JVM implementation mechanism, the reference of a class instance is a pointer to a handle, which is a pair of pointers:
A pointer points to a table, and in fact, this table also has two pointers (one pointer points to a method table containing the object, and the other pointer to a class object, indicating the type to which the object belongs);
Another pointer points to a piece of memory space allocated from the Java heap.
Summarize
(1) Dynamic method calls are implemented by assigning subclass object references to superclass object reference variables.
DerivedC c2=new DerivedC(); BaseClass a1= c2; //BaseClass base class, DerivedC is a1.play() inherited from BaseClass; //play() is defined in BaseClass and DerivedC, that is, the subclass overrides the method
analyze:
* Why can object instances of subclasses be overridden to superclass references?
Automatically achieve upward transformation. Through this statement, the compiler automatically moves the subclass instance upward to become the common type BaseClass;
* a. Will play() execute a method defined by the subclass or a parent class?
Subclass. During the run time, the corresponding method will be obtained based on the object a reference to the actual type. That's why there is polymorphism. An object reference of a base class is given a different subclass object reference. When executing the method, it will show different behaviors.
When a1=c2, there are still two handles, a1 and c2, but a1 and c2 have the same data memory block and different function tables.
(2) The parent object reference cannot be assigned to the child object reference variable
BaseClass a2=new BaseClass(); DerivedC c1=a2;//Error
In Java, upward transformation is automatically carried out, but downward transformation is not. We need to define mandatory progress ourselves.
c1=(DerivedC)a2; Perform forced transformation, that is, downward transformation.
(3) Remember a very simple and complex rule. A type reference can only refer to the methods and variables contained in the reference type itself.
You may say that this rule is wrong, because when the parent class references to the child class object, the subclass method is finally executed.
In fact, this is not contradictory, because later binding is used, and when dynamically running, the subclass method is called according to the type. If the method of the subclass is not defined in the parent class, an error will occur.
For example, in addition to inheriting the functions defined in BaseClass, the DerivedC class also adds several functions (such as myFun())
analyze:
When you use the parent class reference to point to the child class, jvm has actually adjusted the conversion using the type information generated by the compiler.
Here you can understand it this way, which is equivalent to setting functions that are not contained in the parent class to be invisible from the virtual function table. Note that it is possible that some function addresses in the virtual function table have been rewritten in the subclass, so the virtual function item address in the object virtual function table has been set to the address of the method body completed in the subclass.
(4) Comparison of polymorphisms between Java and C++
The solution to polymorphism support for jvm is almost the same as in c++.
However, many compilers in C++ put type information and virtual function information in a virtual function table, but use some technology to distinguish it.
Java separates type information and function information. After inheritance in Java, the subclass will reset its own virtual function table. The items in this virtual function table are composed of two parts. Virtual functions inherited from the parent class and subclasses' own virtual functions.
Virtual function calls are indirectly called through virtual function tables, so polymorphicity can be achieved.
All Java functions, except those declared as final, are bound by late stages.
1 behavior, different objects, their specific manifestations are different.
For example: overloading method overloading and overriding method override
class Human{ void run(){output person is running} } class Man extends Human{ void run(){output man is running} } At this time, the same run, different objects are different (this is an example of method coverage) class Test{ void out(String str){output str} void out(int i){output i} }This example is method overloading, the method name is the same, and the parameter table is different
OK, it's not enough to understand these, so I'll use someone to run for example
Human ahuman=new Man();
In this way, I am equal to instantiating a Man object and declaring a Human reference, letting it point to the Man object, which means that I regard the Man object as Human.
For example, when you go to a zoo, you see an animal and don’t know what it is, “What kind of animal is this?” “This is a giant panda!”
These two sentences are the best proof, because I don’t know that it is a giant panda, but I know that its parent is an animal, so,
This giant panda object is reasonable.
In this way, please note that new Man(); does instantiate the Man object, so the ahuman.run() method outputs "Man is running"
If you write some unique methods like eat() under subclass Man, but Human does not have this method,
When calling the eat method, be sure to pay attention to casting ((Man)ahuman).eat(), so that you can...
For the interface, the situation is similar...
Example:
package domain; //Define superA class superA { int i = 100; void fun(int j) { j = i; System.out.println("This is superA"); } } //Define superA subclass subB class subB extends superA { int m = 1; void fun(int aa) { System.out.println("This is subB"); } } //Define superA subC class subC extends superA { int n = 1; void fun(int cc) { System.out.println("This is subB"); } } //Define superA subC class subC extends superA { int n = 1; void fun(int cc) { System.out.println("This is subC"); } } class Test { public static void main(String[] args) { superA a = new superA(); subB b = new subB(); subC c = new subC(); a = b; a.fun(100); a = c; a.fun(200); } } /*
* In the above code, subB and subC are subclasses of superclass superA. We declare 3 reference variables a, b, in the class Test
* c, Dynamic method calls are implemented by assigning subclass object references to superclass object reference variables. Maybe someone will ask:
* "Why (1) and (2) do not output: This is superA".
* This mechanism of java follows a principle: when a superclass object refers to a variable refers to a subclass object,
* The type of the referenced object rather than the type of the referenced variable determines whose member method is called,
* But this called method must be defined in the superclass.
* That is to say, the method covered by a subclass.
* So, don't be confused by (1) and (2) in the above example. Although it is written as a.fun(), because a in (1) is assigned by b,
* Points to an instance of subclass subB, so the fun() called (1) is actually the member method of subclass subB fun(),
* 它覆盖了超类superA的成员方法fun();同样(2)调用的是子类subC的成员方法fun()。
* 另外,如果子类继承的超类是一个抽象类,虽然抽象类不能通过new操作符实例化,
* 但是可以创建抽象类的对象引用指向子类对象,以实现运行时多态性。具体的实现方法同上例。
* 不过,抽象类的子类必须覆盖实现超类中的所有的抽象方法,
* 否则子类必须被abstract修饰符修饰,当然也就不能被实例化了
*/
以上大多数是以子类覆盖父类的方法实现多态.下面是另一种实现多态的方法-----------重写父类方法
JAVA里没有多继承,一个类之能有一个父类。而继承的表现就是多态。一个父类可以有多个子类,而在子类里可以重写父类的方法(例如方法print()),这样每个子类里重写的代码不一样,自然表现形式就不一样。这样用父类的变量去引用不同的子类,在调用这个相同的方法print()的时候得到的结果和表现形式就不一样了,这就是多态,相同的消息(也就是调用相同的方法)会有不同的结果。 Give an example:
//父类public class Father{ //父类有一个打孩子方法public void hitChild(){ } } //子类1 public class Son1 extends Father{ //重写父类打孩子方法public void hitChild(){ System.out.println("为什么打我?我做错什么了!"); } } //子类2 public class Son2 extends Father{ //重写父类打孩子方法public void hitChild(){ System.out.println("我知道错了,别打了!"); } } //子类3 public class Son3 extends Father{ //重写父类打孩子方法public void hitChild(){ System.out.println("我跑,你打不着!"); } } //测试类public class Test{ public static void main(String args[]){ Father father; father = new Son1(); father.hitChild(); father = new Son2(); father.hitChild(); father = new Son3(); father.hitChild(); } }都调用了相同的方法,出现了不同的结果!这就是多态的表现!
import java.io.*;class Super{ Super(){ System.out.println("This is super class!"); } void method(){ System.out.println("Super's method"); }}class Sub extends Super{ Sub(){ super(); System.out.println("/n/t:and here is the child"); } void method(){ System.out.println("child's method"); }}public class Super_Sub{ public static void main(String[] args){ Super sup=new Sub(); sup.method(); Sub child=(Sub)new Super();//这里,实际分配的内存是Super的,但是却用Child来指代它,这就是“向下转型”(父类冒充子类,因为子类在UML中画时是在下的嘛),必经强制类型转换child.method(); }}对于数据来说,继承是否为正确的设计可以用一个简单的规则来判断。“is-a”规则表明子类的每一个对象都是一个超类的对象。例如,每一个经理是一个员工。然而,只有经理类是员工类的子类才是有意义的。很明显,反过来就不行了――并不是每个员工都是经理。
还有一个明确叙述“is-a”规则的方法是替代原则。该原则规定无论何时,如果程序需要一个超类对象,都可以用一个子类对象来代替
动态绑定
理解调用一个对象方法的机制是非常重要的。下面具体介绍:Xf;
(1)编译器检查对象的声明类型和方法名。
(2)接着,编译器检查方法调用中的参数类型。如果在所有的叫做f的方法中有一个其参数类型同调用提供的参数类型最匹配,那么该方法就会被选择调用。这个过程称作超载选择。(静态)
(3)当程序运行并且使用动态绑定来调用一个方法时,那么虚拟机必须调用同x所指向的对象的实际类型相匹配的方法版本。
...
如果类中没有写构造函数,那么系统会自动为该类提供一个默认构造函数,该构造函数将所有的实例字段初始化为默认值:
...
包用途:
Java允许把多个类收集在一起成为一组,称作包(package)。包便于组织任务,以及使自己的任务和其他人提供的代码库相分离。
标准Java库被分类成许多的包,其中包括java.1ang、java.util和java.net等等。标准Java包是分层次的。就像在硬盘上嵌套有各级子目录一样,可以通过层次嵌套组织包。所有的Java包都在Java和Javax包层次内
创建包
已经看到,已有的库,比如JavaAPI中的类和接口,可以导入到Java程序中。
Java API中的每一个类和接口属于一个特定的包。它包含一组相关联的类和接口,实际是对类和接口进行组织的目录结构。
例如,假定文件名是MyClass.java。它意味着在那个文件有一个、而且只能有一个public类。而且那个类的名字必须是MyClass(包括大小写形式):
packagemypackage;publicclass MyClass{……}创建可复用的类的步骤简要说明如下:
(1)定义一个public类。如果类不是public,它只能被同一包中的其他类使用。
(2)选择一个包名,并把package语句加到可复用的类的源代码文件中。
(3)编译这个类。这样,它就被放到适当的包目录结构中,以供编译器和解译器使用。
(4)把这个可复用的类导入到需要用它的程序中。现在就可以使用它了。
注意在Java语言中可以出现在类定义的括号外面的仅有两个语句,它们是package和import。
包引用---每个类名前加上完整的包名
例如,给出一个指向此包中的类的快捷方式。一旦使用import(导入)了以后,就不再需要给出完整的包名。
可以引入一个特定的类,也可以引入整个包。import语句要放在源文件的头部(但在所有package语句的下面)。例如,可以通过下面的语句引入在java.util包中的所有的类:
importjava.util.*;
然后,就可以使用
Datetoday=new Date();
而不需要在前面加上包名。也可以引入包中某个特定的类:
importjava.util.Date;
要把类放人一个包中,必须把此包的名字放在源文件头部,并且放在对包中的类进行定义的代码之前。例如,在文件Employee.java的开始部分如下:
packagecom.horstmann.corejava;publicclass Employee{……}把包中的文件放入与此完整的包名相匹配的子目录中。例如,在包com.horstmann.corejava中的所有的类文件都必须放在子目录com/horstmann/core.java(Windows下的com/horstmann/corejava)下。这是最简单的一种方法
类被存储在文件系统的子目录中。类的路径必须与所在包名相匹配。
在前面的例子中,包目录com/horstmann/corejava是程序目录的一个子目录。然而这样安排很不灵活。一般,有多个程序需要访问包文件。为了使包可以在多个程序间共享,需要做以下事情:
1)把类放在一个或多个特定的目录中,比如/home/user/classdir。此目录是包树的基本目录。如果加入了类com.horstmann.corejava.Employee,那么此类文件必须位于子目录/home/user/classdir/com/horstmann/corejava下。
2)设置类路径。类路径是其子目录包含类文件的所有基本目录的集合。classpath
已经接触过public和private访问指示符。
被标记为Public的部件可以被任何类使用,而私有部件只能被定义它们的类使用。如果没有指定public或private,那么部件(即类、方法或变量)可以被同一个包中的所有方法访问。
Java API包
为了简化面向对象的编程过程,Java系统事先设计并实现了一些体现了常用功能的标准类,如用于输入/输出的类,用于数学运算的类,用于图形用户界面设计的类,用于网络处理的类等。这些系统标准类根据实现的功能不同,可以划分成不同的集合,每个集合是一个包,合称为类库。可以引用这些包,也可以创建自己的包。
Java的类库是系统提供的已实现的标准类的集合,是Java编程的API,它可以帮助开发者方便、快捷地开发Java程序
接口主要作用是可以帮助实现类似于类的多重继承的功能。在Java中,出于简化程序结构的考虑,不再支持类间的多重继承而只支持单重继承,即一个类至多只能有一个直接父类。然而在解决实际问题的过程中,仅仅依靠单重继承在很多情况下都不能将问题的复杂性表述完整,需要其他的机制作为辅助。
接口声明
Java中声明接口的语法如下:
[public] interface 接口名[extends 父接口名列表]{ //接口体;//常量域声明[public] [static] [final] 域类型域名=常量值; //抽象方法声明[public] [abstract] 返回值方法名(参数列表) [throw异常列表];}从上面的语法规定可以看出,定义接口与定义类非常相似,实际上完全可以把接口理解成为一种特殊的类,接口是由常量和抽象方法组成的特殊类
(1)接口中的属性都是用final修饰的常量,
(2)接口中的方法都是用abstract修饰的抽象方法,在接口中只能给出这些抽象方法的方法名、返回值和参数列表,而不能定义方法体,即仅仅规定了一组信息交换、传输和处理的“接口”
接口的实现
一个类要实现某个或某几个接口时,有如下的步骤和注意事项:
(1)在类的声明部分,用implements关键字声明该类将要实现哪些接口;
as follows:
class类名implements接口{ }(2)如果实现某接口的类不是abstract的抽象类,则在类的定义部分必须实现指定接口的所有抽象方法,即为所有抽象方法定义方法体,而且方法头部分应该与接口中的定义完全一致,即有完全相同的返回值和参数列表;
(3)如果实现某接口的类是abstract的抽象类,则它可以不实现该接口所有的方法。
(4)一个类在实现某接口的抽象方法时,必须使用完全相同的方法头。
(5)接口的抽象方法,其访问限制符都已指定是public,所以类在实现方法时,必须显式地使用public修饰符。
summary:
多重继承是指一个子类继承多个父类。Java不支持多重继承,但Java提供了接口。
子类不能访问父类的private成员,但子类可以访问其父类的public,protected和包访问成员;要访问父类的包访问成员,子类一定要在父类的包内。
子类构造函数总是先调用(显式的或隐式地)其父类的构造函数,以创建和初始化子类的父类成员。
子类的对象可以当作其父类的对象对待,反之则不行(即向上转型)
protected访问是public和private访问之间一个保护性的中间层次。父类方法、子类方法和在同一个包内类的方法都能访问父类的protected成员,但其他方法均不能访问
一个子类对象引用可以隐式地转换成一个父类对象引用。使用显式的类型转换,可以把父类引用转换成子类引用。如果目标不是子类对象,将产生ClassCastException例外处理。