Java Learning note 6--class inheritance, object class

Source: Internet
Author: User
Tags class manager getcolor ming

1. Inheritance of classes

A mechanism for creating new classes from existing classes is one of the cornerstones of object-oriented programming. With inheritance, new classes can be defined based on existing classes, and new classes have all the functionality of existing classes

Java only supports single inheritance, each subclass can have only one direct parent class, the parent class is a collection of public properties and methods of all subclasses, the subclass is the specialization of the parent class, and the inheritance mechanism can improve the abstraction degree of the program and improve the reusability of the code.

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

Derived classes (Derived-class), also called subclasses (subclass), inherit classes from other classes and inherit the state and behavior of all ancestors. Derived classes can add variables and methods, and derived classes can override (override) inherited methods

The relationship between the subclass object and the parent object exists "is A" (or "is kind of")

The derived class produces an object that, externally, should include the same interface as the base class and can have more methods and data members containing a child object of a base class type

Inherited syntax:
extends ParentClass {//Class body}

As an example:

In a company, there are two categories of staff (Employees) and managers (Magagers):

Possible attribute information for a staff object (Employees) includes:

– Employee number (EmployeeNumber)

– Names (name)

– Address

– Phone number (PhoneNumber)

Administrative Personnel (Managers) may have the following properties in addition to the properties of the ordinary employee:

– Responsibilities (Responsibilities)

– Managed staff (Listofemployees)

Class diagram for employee and manager:

Parent class Employeeclass employee{        int  Employeenumbe;    String  name, address, PhoneNumber;} Subclass Managerclass  Manager extends Employee {    //subclass added data member    String responsibilities, listofemployees;}

There are three classes: person, Employee, 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     S Tring 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 ());}  }
Operation Result:

Li Ming

123456

He Xia

543469

Internet Project

Description: A subclass cannot directly access private properties and methods inherited from a parent class, but can be accessed using the public (and protected) method, as shown in the following example:

public class B {public     int a = ten;     private int b =;     protected int c =;     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);        System.out.println (GETB ()) is not allowed;        Allow         System.out.println (c);             Allow     }}

Hide and overwrite

Subclasses can redefine attribute variables and methods inherited from the parent class to see a simple example:

Class Parent {number    anumber;} Class Child extends Parent {    Float anumber;}

Properties are hidden:

When a child class declares the same member variable name as the parent class, the variable inherited from the parent class is hidden

Subclasses have two variables of the same name, one inherits from the parent class, and the other is declared by itself, when the subclass performs an operation inherited from the parent class, handles the variable inherited from the parent class, and when the subclass executes its own declared method, it is manipulating its own declared variables

How do I access the hidden parent class properties?

Invoking a method inherited from a parent class, the property that inherits from the parent class is manipulated, using super. Properties

Examples of hidden properties:

Class a1{    int x = 2;        public void setx (int i) {           x = i;    }    void Printa ()    {       System.out.println (x);    }  } Class B1 extends a1{    int x = n;    void Printb ()     {        super.x = super.x +;        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 ();    }  }
Operation Result:

4

super.x= x= 100

12

super.x= x= 100

16

4

Subclasses cannot inherit static properties from the parent class, but can manipulate static properties in the parent class. As in the example above, "int x = 2;" Change to "static int x = 2;", then compile and run the program and get the following result

Method overrides

If a subclass does not need to use the functionality of a method inherited from a parent class, you can declare your own method, called a method override, with the same name. The return type of the overridden method, the method name, and the number and type of arguments must be the same as the method being overridden

overriding methods and overridden methods can be distinguished by using different class names or non-homogeneous object names in front of the method name, and access to the overridden method may be looser than overridden, but not more restrictive

Methods covered by the application:

    • Implements the same functionality as the parent class in a subclass, but with different algorithms or formulas

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

    • A method that inherits from a parent class needs to be canceled in a subclass

Methods that must be overridden

Derived classes must override the abstract methods in the base class, or the derived class itself becomes an abstract class.

Methods that cannot be overridden

Finalization method declared as final in the base class

Static methods declared as static in the base class

Calling the overridden method

Super.overriddenmethodname ();

The construction method with inheritance is guided by the following principles:

Subclasses cannot inherit construction methods from parent class

A good program design method is to call a parent class construction method in the constructor of a subclass, the calling statement must appear in the first row of the subclass construction method, and you can use the Super keyword

If the parent class construction method is not explicitly called in the declaration of a subclass construction method, the system will automatically invoke the default constructor of the parent class (that is, the parameterless constructor method) when it executes the child class's constructor method.

To give an example:

public class Person {protected String name, PhoneNumber, address;      Public person () {This ("", "", "");         The public person (string aName, String aphonenumber, String anaddress) {name=aname;         Phonenumber=aphonenumber;      address=anaddress;        }} public class Employee extends person {protected int employeenumber;       Protected String workphonenumber;  Public Employee () {///here implicitly calls the constructor method person () This (0, ""); The public Employee (int anumber, String aphonenumber) {///here implicitly calls the constructor method person () Employeenumb           Er=anumber;       Workphonenumber = Aphonenumber;             }} public class Professor extends Employee {protected String;            Public professor () {super ();              "";           } public professor (int anumber, string aphonenumber, String aresearch) {super (anumber, Aphonenumber); Aresearch;        }} 
2. Object class

The direct or indirect parent class of all classes in a Java program, the parent class of all classes in the class library, at the highest point in the class hierarchy, contains the public properties of all Java classes, constructed by object ()

The object class defines the state and behavior that all objects must have, and the more important methods are as follows

–public final Class getclass ()

Gets the class information that the current object belongs to, returning a class object

–public String toString ()

Returns information about the current object itself, returned by a string object

–public boolean equals (Object obj)

Compares whether two objects are the same object, yes returns true

–protected Object Clone ()

Generates a copy of the current object and returns the copied object

–public int Hashcode ()

Returns the hash code value of the object

–protected void Finalize () throws Throwable

Defines the resource release work that is required to complete the collection of the current object

Your class cannot overwrite the finalization method, that is, the method with the final decoration

Concepts of equality and the same

Two objects have the same type, and the same property values, are said to be equal (equal)

If two reference variables point to the same object, the two variables (objects) are said to be the same (identical)

Two objects are the same, they must be equal; two objects are equal, not necessarily the same

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

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

Equals method

Because object is a tree root node in a class hierarchy, all other classes inherit the Equals () method. The Equals () method in the object class is defined as follows, and is also a judge of whether two objects are the same

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

Examples of the use of the Equals method in the object class:

public class equalstest{public    static void Main (String args[]) {    BankAccount a = new BankAccount ("Bob", 123456, 10 0.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 in the BankAccount class, because the Equals method in the object class is overridden, so the method definition header must be exactly the same as 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 ())); }

Examples of application of 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;      }}
Operation 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

Constructs a new object based on an existing object; is defined as protected in the root class object, so it needs to be overwritten as public; Implements the Cloneable interface to give an object the ability to be cloned (cloneability)

Class MyObject implements cloneable{  //...}

Finalize method

The system automatically invokes the Finalize method of the object before the object is reclaimed by the garbage collector; If you want to overwrite the Finalize method, you must call Super.finalize at the end of the overriding method

GetClass method

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

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

void Printclassname (Object obj) {      System.out.println ("The object's class is" + Obj.getclass (). GetName ());}

Notify, Notifyall, wait methods

Final method, cannot overwrite, these three methods are mainly used in multi-threaded program

Java Learning note 6--class inheritance, 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.