Dark Horse Programmer (Java)----Object-oriented (middle)

Source: Internet
Author: User
Tags getcolor

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

3.1 Overview of inheritance

inheritance is an important feature of object-oriented. When the same properties and behaviors exist in multiple classes, the content is extracted into a single class, so that multiple classes do not need to define these properties and behaviors, as long as the class is followed. At this point, multiple classes can be called subclasses, and a separate class is called a parent class or a superclass.

Benefits of Inheritance:

1, improve the reusability of the Code

2, improve the maintenance of the Code

3, let the class and the relationship between the class, is the premise of polymorphism

Disadvantages of Inheritance:

Class has a relationship with the class, but it is also a disadvantage of inheritance, because the coupling of the class is enhanced.


Inherited usage: Java uses the extends keyword to represent subclasses inheriting the parent class, using the format: Class subclass name extends the parent class name. Example:

class Person {public void eat () {System.out.println ("eat");} public void Sleep () {System.out.println ("Sleeping");}} Class Student extends Person {}class Teacher extends person {}class Extendsdemo {public static void main (string[] args) {S tudent s = new Student (); S.eat (); S.sleep (); System.out.println ("-------------"); Teacher t = new Teacher (); T.eat (); T.sleep ();}}
Operation Result:

3.2 Characteristics of the inheritance

1. Java only supports single inheritance and does not support multiple inheritance.

2, Java support multi-layer inheritance (inheritance system). Example: Class Son extends Father {}; Class Father extends Grandfather {}

3.3 Considerations for Inheritance

1. Subclasses can only inherit all non-private members of the parent class (member methods and member variables)

2. Subclasses cannot inherit the construction method of the parent class, but can access the parent class construction method through the Super keyword.

3. Do not inherit for part of the function

3.4 Inheriting the relationship of the member of the Neutron parent class

3.4.1 Super keyword

This and super are very similar in usage, this represents a reference to this class of objects, andsuper represents the identity of the memory space of the parent class (which can be understood as a parent class reference that can manipulate members of the parent class). when the member variable and local variable of this class have the same name as this, the member variable in the child parent class is distinguished with the same name as Super.

This invokes member variables, constructor methods, and member methods in the current class, and super calls member variables, constructor methods, and member methods in the parent class, and when the constructor method is called, the statement must be the first sentence of the construction method.

Characteristics of variables in 3.4.2 parent class

If a non-private member variable with the same name appears in the subclass, the subclass accesses the member variable in this class, using this. Subclass to access a member variable of the same name in the parent class, use super. This represents a reference to this class of objects. Super represents a reference to a parent class object. Example:

Class Father {public int num = 10;} Class Son extends Father {public int num = 20;public void show () {int num = 30; SYSTEM.OUT.PRINTLN (num); System.out.println (This.num); System.out.println (Super.num);}} Class ExtendsDemo5 {public static void main (string[] args) {Son s = new Son (); S.show ();}}
Operation Result:

The characteristics of the construction method in the 3.4.3 sub-parent class

all constructor methods in a subclass access the constructor of the parent's hollow parameter by default, that is, the constructor of the parent class is run first when the child class object is initialized. Because the constructor of the subclass defaults to the first row with an implicit statement super (), super () accesses the constructor of the parent hollow parameter, and all constructors in the subclass default to the first line is super (). Example:

Class Father {int Age;public Father () {System.out.println ("non-parametric construction method of Father");} Public Father (String name) {System.out.println ("Father with parameter construction method");}} Class Son extends Father {public Son () {//super ();  The system will add super () to this place by default; System.out.println ("Son's method of non-argument construction");} Public Son (String name) {//super ();  The system will add super () to this place by default; System.out.println ("The method of constructing the Son");}} Class ExtendsDemo6 {public static void main (string[] args) {son s = new Son (); System.out.println ("------------"); Son s2 = new Son ("Hammer");}}
Operation Result:


What if there are no arguments in the parent class when constructing the method?

If there is no parameterless constructor in the parent class, you can use the Super keyword to display the parameter construction method of the calling parent class, or you can call the other constructor methods of this class through the This keyword, but you must ensure that there is a constructor method in the subclass that accesses the constructor of the parent class. Since the subclass object is initialized, the parent class must be initialized first. Example:

Class Father {public Father (String name) {System.out.println ("Father with parameter construction method");}} Class Son extends Father {public Son () {super ("name"); System.out.println ("Son's method of non-argument construction");} Public Son (String name) {this (); System.out.println ("Son's Method---" +name);}} Class ExtendsDemo7 {public static void main (string[] args) {son s = new Son (); System.out.println ("----------------"); Son ss = new Son ("Hammer");}}


Operation Result:


The characteristics of member methods in the 3.4.4 child parent class

creates an object of a subclass that can call methods in the parent and child classes, respectively. When a method in a child class calls the method with the same name in the child's parent class, the method in the subclass is executed, not the method in the parent class, which is called the override of the method, also called an override (override).

1, how to determine whether to rewrite (override)?

1), two classes with a parent-child relationship.

2), the parent class and the subclass each have a function, the definition of the other function (return value type, function name, parameter list) is identical.

Class Phone {public void call (String name) {System.out.println ("to" +name+ ")}} class Newphone extends phone {public voi D Call (String name) {//system.out.println ("+name+"); Super.call (name); System.out.println ("You can see the picture while you are on the phone");}} Class ExtendsDemo9 {public static void main (string[] args) {Newphone np = new Newphone (); Np.call ("Hammer Brother");}}

Operation Result:


2. Method override (override) considerations

1), private methods in the parent class cannot be overridden because the parent class private method subclass simply cannot inherit

2), subclasses overriding the parent class method, access permissions can not be lower than the parent class of the method's permissions, preferably consistent.

3), parent static methods, subclasses must also be overridden by static methods

3. Comparison method overloading (overload) and override (override)

1), overloaded two functions exist in the same class; The overridden two functions exist in two classes that have a parent-child relationship.

2), overloaded function names are the same, parameter lists (parameter types and number of parameters) are different; The overridden return value type, function name, and parameter list are the same.  

Example: Requirements: Create a class of animals, member variables have Name,age,color, the construction method consists of both the parameter and the non-parameter, the member method has getxxx (), setxxx (), eat (). Then let cat inherit it and replicate the Eat () method.

Class Animal{private string name;private int age;private string Color;public Animal () {}public Animal (string Name,int age, String Color {this.name = Name;this.age = Age;this.color = color;} public void Eat () {System.out.println ("Don't sleep, it's time to eat");} public void SetName (String name) {this.name = name;} Public String GetName () {return name;} public void Setage (int.) {this.age = age;} public int getage () {return age;} public void SetColor (String color) {this.color = color;} Public String GetColor () {return color;}} Class Cat extends Animal{public cat () {}public cat (String name,int age,string color) {super (name,age,color);} public void Eat () {System.out.println ("I'm Eating");}} Class Extendstest5{public static void Main (string[] args) {//mode 1Cat C1 = new Cat () c1.setname ("Floret"); C1.setage (2); C1.setcolor ("Black and White"); System.out.println (C1.getname () + "---" +c1.getage () + "---" +c1.getcolor ()); C1.eat ();//mode 2Cat C2 = new Cat ("Floret", 2, "Black and White") ; System.out.println (C1.getname () + "---" +c1.getage () + "---" +c1.getcolor ()); C2.eat ();}}
Operation Result:



3.5 sub-class instantiation process

Take Zi z = new Fu (20) For example

1. Load the Zi.class file into memory, because the Zi class inherits the Fu class, it also loads the Fu.class file into memory. 2, in the stack memory for S open space. 3, in the heap of memory for students to open up space for objects. 4. Default initialization for the member variable age of the Zi class (the variable of type int has a default value of 0). 5. The age member variable for the Zi class is displayed initialized in the parent class (int age = 1). 6. Initialize the age member variable by constructing the parent class (int age = 2). 7. Display initialization in subclasses (int age = 3). 8. Initialize the age by the method of constructing the subclass (int age = 4). 9. The object is constructed, and the address is assigned to the z variable.

Verify:

Class Fu{int age = 1;public Fu () {System.out.println [age]; age = 2; System.out.println (age);}} Class Zi extends Fu{int age = 3;public Zi () {System.out.println [age]; age = 4; System.out.println (age);}} Class Test{public static void Main (string[] args) {Zi z = new Zi ();}}

Operation Result:


3.6 Final keyword

1, final translation into Chinese is the meaning of "final", you can modify classes, variables and functions.  

A class that is final decorated cannot be inherited.

The final modified method cannot be replicated.

A final modified variable (a member variable and a local variable) is a constant and can only be assigned once.

An inner class can only access a final decorated local variable.

2, the writing standard of constants

Capitalize all letters.

If it is made up of multiple words, the words are connected by "_" between them.  

3. Final modification of local variables

    /* Interview title: The problem basic type of the final modifier local variable    : The value of the base type cannot be changed.    Reference type: The address value of the reference type cannot be changed, but the value of the heap memory of the object can be changed. */class Student {int = 10;} Class Finaltest {public static void main (string[] args) {//local variable is the base data type int x = 10;x = 100; SYSTEM.OUT.PRINTLN (x); final int y = 10;//cannot assign a value to the final variable y//y = 100; System.out.println (y); System.out.println ("--------------");//local variable is the reference data type Student s = new Student (); System.out.println (s.age); s.age = 100; System.out.println (S.age); System.out.println ("--------------"); final Student ss = new Student (); System.out.println (ss.age); ss.age = 100;//object reference the value in the heap memory referred to is can be changed System.out.println (ss.age);//Reallocate memory space//cannot assign a value to the final variable SS SS = new Student ();}}
Operation Result:

Conclusion: Basic type: The value of the basic type cannot be changed.

Reference type: The address value of the reference type cannot be changed, but the value of the heap memory of the object can be changed.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse Programmer (Java)----Object-oriented (middle)

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.