Java Study Notes 6 -- class inheritance, Object class, and study notes 6 --

Source: Internet
Author: User
Tags class manager getcolor

Java Study Notes 6 -- class inheritance, Object class, and study notes 6 --

Next, we learned the following:

Java study notes 5-Class Method

Java Study Notes 4-basic concepts of classes and objects (2)

Java Study Notes 3-basic concepts of classes and objects (1)

Java study Note 2 -- data type, array

Java study Note 1-Summary of the development environment Platform

URL: http://www.cnblogs.com/archimedes/p/java-study-note6.html.

1. class inheritance

A mechanism for creating new classes from existing classes is one of the cornerstones of object-oriented programming. Through inheritance, you can define new classes based on existing classes. New classes have all the functions of existing classes.

Java only supports single inheritance. each subclass can only have one direct parent class. The parent class is a set of public attributes and methods of all subclasses, and the Child class is the specialization of the parent class, the Inheritance Mechanism can improve the abstract degree of the program and the reusability of the Code.

Base class, also known as superclass, is a class that is directly or indirectly inherited.

A derived class (derived-class), also known as a subclass (subclass), inherits the classes obtained from other classes and inherits the statuses and behaviors of all the ancestors. You can add variables and methods to a derived class. The derived class can also overwrite the inherited methods.

A subclass object has A "is a" (or "is kind of") Relationship with its parent class object.

The object generated by the derived class. From the external point of view, it should include the same interface as the base class. It can have more methods and data members, including a base class sub-object.

Inherited Syntax:
Class childClassExtendsParentClass {// class body}

For example:

In a company, there are two types of Employees (Employees) and management personnel (Magagers:

Employee (Employees)Possible attributes include:

-Employee ID (employeeNumber)

-Name)

-Address)

-PhoneNumber)

Managers)In addition to attributes of common employees, they may also have the following attributes:

-Responsibilities)

-Managed staff (listOfEmployees)

Class Diagram of Employee and Manager:

// Parent class Employeeclass Employee {int employeeNumbe; String name, address, phoneNumber;} // subclass Managerclass Manager extends Employee {// String responsibilities, listOfEmployees, a data member added to the subclass ;}

There are three types: Person, Employee, and Manager. Its Class Level

public class Person {    public String name;    public String getName() {         return name;     }} public class Employee extends Person {     public int employeeNumber;     public int getEmployeeNumber() {         return employeeNumber;     } } public class Manager extends Employee {     public String responsibilities;     public String getResponsibilities() {         return responsibilities;    } }

Test procedure:

public class Test {  public static void main(String args[]){    Employee li = new Employee();     li.name = "Li Ming";     li.employeeNumber = 123456;     System.out.println(li.getName());    System.out.println(li.getEmployeeNumber());         Manager he = new Manager();     he.name = "He Xia";     he.employeeNumber = 543469;               he.responsibilities = "Internet project";     System.out.println(he.getName());     System.out.println(he.getEmployeeNumber());    System.out.println(he.getResponsibilities());  }}
Running result:

Li Ming

123456

He Xia

543469

Internet project

Note: The subclass cannot directly access the private attributes and methods inherited from the parent class, but the public (and protected) methods can be used for access, as shown in the following example:

Public class B {public int a = 10; private int B = 20; protected int c = 30; public int getB () {return B ;}} public class A extends B {public int d; public void tryVariables () {System. out. println (a); // allow System. out. println (B); // The System is not allowed. out. println (getB (); // allow System. out. println (c); // allowed }}

Hide and overwrite

Subclass can redefine the property variables and methods inherited from the parent class. Here is a simple example:

class Parent {    Number aNumber;}class Child extends Parent {    Float aNumber;}

Hide attributes:

The subclass declares the same member variable name as the parent class, and the variables inherited from the parent class are hidden.

The subclass has two variables with the same name. One is inherited from the parent class, and the other is declared by itself. When the subclass executes the operation inherited from the parent class, the processing is a variable inherited from the parent class, and when the subclass executes its own declared method, the operation is the variable it declares.

How to access hidden parent attributes?

If you call a method inherited from the parent class, the operation is performed on the attributes inherited from the parent class, and the super. attribute is used.

Example of hiding an attribute:

class A1{    int x = 2;        public void setx(int i){           x = i;    }    void printa()    {       System.out.println(x);    }  }class B1 extends A1{    int x = 100;    void printb()     {        super.x = super.x + 10 ;        System.out.println("super.x= " + super.x + "  x= " + x);    }  }

Test procedure:

Public class Test {public static void main (String [] args) {A1 a1 = new A1 (); a1.setx (4); a1.printa (); B1 b1 = new B1 (); b1.printb (); b1.printa (); b1.setx (6); // set the inherited x value to 6 b1.printb (); b1.printa (); a1.printa ();}}
Running result:

4

Super. x = 12 x = 100

12

Super. x = 16 x = 100

16

4

A subclass cannot inherit static attributes of the parent class, but can operate on static attributes of the parent class. For example, in the preceding example, change "int x = 2;" to "static int x = 2;", and then compile and run the program. The following result is displayed:

Method coverage

If the subclass does not need to use the function of inheriting methods from the parent class, it can declare its own method with the same name, called method overwrite. Override the return type, method name, number and type of parameters of the method must be the same as that of the overwritten method.

You only need to use different class names or object names before the method name to distinguish between the override method and the override method. The access permission of the override method can be loose than that of the overwritten method, but it cannot be stricter.

Application scenarios covered by methods:

  • Sub-classes implement the same functions as parent classes, but different algorithms or formulas are used.

  • In methods with the same name, do more things than the parent class

  • Remove the method inherited from the parent class in the subclass.

Method that must be overwritten

A derived class must overwrite the abstract methods in the base class. Otherwise, the derived class itself becomes an abstract class.

Method that cannot be overwritten

Final termination method in the base class

Static Methods declared as static in the base class

Call the overwritten Method

Super. overriddenMethodName ();

Constructor methods for inheritance follow the following principles:

Subclass cannot inherit constructor from parent class

A good programming method is to call a parent class constructor In the constructor of the subclass. The Calling statement must appear in the first line of the subclass constructor. The super keyword can be used.

If the parent class constructor is not explicitly called in the subclass constructor declaration, the system automatically calls the default constructor of the parent class when executing the constructor of the subclass (that is, the constructor without parameters)

For example:

Public class Person {protected String name, phoneNumber, address; public Person () {this ("", "", "") ;}public Person (String aName, String aPhoneNumber, string anAddress) {name = aName; phoneNumber = aPhoneNumber; address = anAddress;} public class Employee extends Person {protected int Employee number; protected String workPhoneNumber; public Employee () {// here, the Construction Method Person () this (0, "");} public Employee (int aNumber, String aPhoneNumber) is implicitly called. {// here, the Construction Method Person () is implicitly called () employeeNumber = aNumber; workPhoneNumber = aPhoneNumber ;}} public class extends sor extends Employee {protected String research; public extends sor () {super (); research = "";} public partition sor (int aNumber, String aPhoneNumber, String aResearch) {super (aNumber, aPhoneNumber); research = aResearch ;}}
2. Object Class

The direct or indirect parent class of all classes in the Java program. The parent class of all classes in the class library is at the highest point of the class level and contains the public attributes of all Java classes, the constructor is Object ()

The Object class defines the states and actions that all objects must have. The main method is as follows:

-Public final Class getClass ()

Obtains the Class information of the current object and returns the Class object.

-Public String toString ()

Returns information about the current object by string object.

-Public boolean equals (Object obj)

Returns true if two objects are the same.

-Protected Object clone ()

Generate a copy of the current object and return the copy object

-Public int hashCode ()

Returns the hash code value of the object.

-Protected void finalize () throws Throwable

Define the resource release work to be completed when the current object is recycled

Your class cannot overwrite the final method, that is, the final modification method.

Equal and same concept

The two objects have the same type and the same property value, and they are equal (equal)

If the two referenced variables point to the same object, the two variables are called the same (identical)

Two objects must be equal if they are the same. Two objects must be equal, not necessarily the same.

The comparison operator "=" determines whether the two objects are the same

// Determine whether two objects are the same public class test {public static void main (String args []) {BankAccount a = new BankAccount ("Bob", 123456,100.00 f ); bankAccount B = new BankAccount ("Bob", 123456,100.00 f); if (a = B) System. out. println ("YES"); else System. out. println ("NO ");}}

Equals Method

Because the Object is a root node in the class hierarchy, all other classes inherit the equals () method. The equals () method in the Object class is defined as follows. It can be seen that it is also used to determine whether two objects are the same

public boolean equals(Object x) {     return this == x; }

Example of using the equals method in the Object class:

public class EqualsTest{    public static void main(String args[]){    BankAccount a = new BankAccount("Bob", 123456, 100.00f);     BankAccount b = new BankAccount("Bob", 123456, 100.00f);         if (a.equals(b))           System.out.println("YES");         else            System.out.println("NO");    }}

Add the equals method to the BankAccount class. Because the equals method in the Object class is overwritten, the method definition header must be identical to the equals method in the Object class.

public boolean equals(Object x) {     if (this.getClass() != x.getClass())       return false;          BankAccount b = (BankAccount)x;         return        ((this.getOwnerName().equals(b.getOwnerName()))        &&(this.getAccountNumber() == b.getAccountNumber())       &&(this.getBalance() == b.getBalance())); }

Example of applying the equals method:

public class Apple {       private String color;       private boolean ripe;        public Apple(String aColor, boolean isRipe) {            color = aColor;            ripe = isRipe;       }            public void setColor(String aColor) { color = aColor;  }            public void setRipe(boolean isRipe) { ripe = isRipe; }           public String getColor() { return color; }           public boolean getRipe() { return ripe; }      public String toString() {          if (ripe)  return("A ripe " + color + " apple");          else  return("A not so ripe " + color + " apple");       }       public boolean equals(Object obj) {           if (obj instanceof Apple) {                Apple a = (Apple) obj;                return (color.equals(a.getColor()) && (ripe == a.getRipe()));           }           return false;      }}
Running result:

A ripe red apple is equal to A ripe red apple: true

A is identical to B: false

A ripe red apple is equal to A ripe red apple: true

A is identical to c: true

Clone Method

Construct a new Object based on an existing Object. It is defined as protected in the root class Object, so it must be overwritten as public. Implement the Cloneable interface, assign cloneability to an object to be cloned)

class MyObject implements Cloneable{  //…}

Finalize method

Before the object is recycled by the garbage collector, the system automatically calls the finalize method of the object. to override the finalize method, the super. finalize method must be called at the end of the overwriting method.

GetClass Method

The final method returns a Class object, which represents the Class to which the object belongs.

Through the Class object, you can query various information of the Class object, such as its name, its base Class, and the name of the interface it implements.

void PrintClassName(Object obj) {      System.out.println("The Object's class is " + obj.getClass().getName());}

Notify, policyall, and wait Methods

The final method cannot be overwritten. These three methods are mainly used in multi-threaded programs.

References:

Java programming-Tsinghua University

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.