Java Note 3: inheritance)

Source: Internet
Author: User

For example:

The code is as follows: Copy code
Class Manager extends Employee
{
// The Manager class inherits the Employee class and adds the new method setBonus and the new domain bonus.
Public void setBonus (double s)
      {
Bonus = s;
      }
...
Private double bonus;
}

1. Subclass method override (override) superclass method

Assume that the Manager class inherits from the Employee class. The Employee class has three domains: name, salary, and hireDay, and the Manager adds a bonus domain. The Employee method is getSalary (). Currently, the salary calculation method of the Manager is different. You need to override getSalary () to overwrite this method of the Employee class.

Note that sub-classes cannot directly access the private domain of the super class (assuming that salary is a private domain), the following method cannot be used:

Public double getSalary ()
{
Return salary + bonus; // error. salary cannot be accessed
}

Java uses another method to solve the above problem, that is, to obtain the value of the domain using the superclass method introduction.

Public double getSalary ()
{
Return super. getSalary () + bonus;
}

Note: super is not an object reference and cannot be overwritten with another object variable. It is only a special keyword that instructs the compiler to call a superclass method.

Another application of super is in the constructor. The subclass constructor needs to call some constructor of the superclass to initialize a superclass domain (especially a private domain ).

The code is as follows: Copy code

Public Manager (String n, double s, int year, int month, int day)
{
// Call the constructor that contains the n, s, year, month, and day parameters in the superclass
Super (n, s, year, month, day );
Bonus = 0;
}

2. Inheritance level

A set of all classes derived from a public superclass is called an inheritance level (inheritance hierarchy ), the path from a specific class to its ancestor in the hierarchy is called the inheritance chain of this class ).

 
3. polymorphism and dynamic binding)

An object variable can reference multiple types of symptom polymorphism;

Dynamic binding is a phenomenon in which you can automatically select the method to call during running.

For example:

The code is as follows: Copy code

Manager boss = new Manager ("boss", 80000,198 7, 12, 15 );
Boss. setBonus (5000 );

Employee [] staff = new Employee [3];

Staff [0] = boss;
Staff [1] = new Employee ("Employee _ 1", 50000,198, 3, 23 );
Staff [2] = new Employee ("employee_2", 50000,199, 22 );

// Polymorphism: variable e can reference both the Manager object and the Employee object.
// Dynamic binding: Call the getSalary () method of the Employee class when variable e references the Employee object
// Call the getSalary () method of the Manager class when referencing the Manager object
For (Employee e: staff)
System. out. println (e. getName () + "" + e. getSalary ());
Polymorphism:

Employee e;
E = new Employee (...); // OK
E = new Manager (...); // OK
// However, super variables cannot reference subclass objects.
Employee a = new Employee (...);
Manager m = a; // error dynamic binding:

Detailed execution process of object methods:

① The compiler checks the declared type and method name of the object and obtains all candidate methods that may be called;

② The compiler checks the parameter types provided when a method is called. If the parameter types of a candidate method are identical, select this method. This process is called overloading resolution );

③ The name and parameter type of the method to be called have been obtained in the previous two steps. If the method is private, static, final, or constructor, the compiler can accurately know which method to call. This method is called static binding ). Correspondingly, the called method depends on the actual type of implicit parameters and is dynamically bound at runtime;

④ When a dynamic binding call method is used, the virtual machine must call the method of the class that is most suitable for the actual type of the object referenced by the implicit parameter.

Note: To avoid searching for methods every time, the VM creates a method table for each class in advance, which lists the signatures of all methods and actually called methods. You only need to look up the table, so it is faster.

4. Block inheritance: final classes and methods

If the class is declared as final, other classes will inherit the class. Declare the method in the class as final, and the subclass will not be able to override this method. All methods in the final class are automatically called final methods.

The code is as follows: Copy code
Final class Executive extends Manager
{
...
} Class Employee
{
...
Public final String getName ()
      {
Return name;
      }
...
}

Note: the domain can also be declared as final. For the final domain, the value of the final domain cannot be modified after the object is constructed. The main reason we declare a method or class as final is to ensure that they do not change the semantics in the subclass. Some programmers suggest declaring all methods as final unless we have enough reason to use polymorphism. This reduces the system overhead caused by the dynamic binding process and improves program performance. However, with the development of Java virtual machines, the processing capability is getting stronger and stronger, and the compiler can know the inheritance relationship between classes in a very short time, and can quickly detect whether there are overwriting methods.

5. Forced type conversion

• Type conversion can only be performed within the inheritance level
• Use instanceof for check before converting a superclass to a subclass

The code is as follows: Copy code
Employee [] staff = new Employee [3];
Staff [0] = new Manager (...);
Staff [1] = new Employee (...);
Staff [2] = new Employee (...);
 
Manager boss;
If (staff [1] instanceof Manager)
{
Boss = (Manager) staff [1];
}

6. Abstract class

Abstract classes and abstract methods are declared with abstract keywords.
Classes that contain one or more abstract methods must be declared as abstract classes.
In an abstract class, you can also implement fields and specific methods.
Abstract classes cannot be instantiated, that is, they cannot be created.

The code is as follows: Copy code

Abstract class Person
{
Public Person (String n)
      {
Name = n;
      }
     
Public abstract String getDescription ();

Public String getName ()
      {
Return name;
      }

Private String name;
}

Although we cannot instantiate an abstract class, we can define an object variable of an abstract class, but it can only reference objects of non-abstract subclass. For example:

// The Student class here is a subclass of the Person class
Person p = new Student ("Raysmond", "1024"); 7. Protected access

• Private -- only visible to this class
• Public -- visible to all classes
• Protected-visible to this package and all subclasses
• This package is visible by default
8. Super class of the class-Object class

The superclass of all classes in Java are objects, which do not need to be declared in the class. Every class in Java is derived from it. Pay attention to two points.

• Any Object can be referenced using an Object-type variable
Object obj = new Student ("Raysmond", "1024"); • In Java, only the basic type is not an Object, and other data types, such as arrays, are all objects, are extended to the Object class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.