Week 3 of getting started with Java
preface
The third week of learning Java from scratch
1, Continue object oriented
1. What is inheritance?
Extract the common contents of multiple classes into an independent class, and then multiple classes have a relationship with the independent class:
This is inheritance!
Key words: Extensions
Writing format:
class Fu{} class zi extends Fu{}
Benefits of inheritance
1. I mprove code maintainability
II. Improve code reusability
3. It is the premise of polymorphism to make a connection between classes
Before using inheritance, if multiple classes need to use the same method, the same method must be defined repeatedly in each class, which greatly improves the redundancy of code and reduces the redundancy by using inheritance
//Before using inheritance Student class class Student{ Define member methods public void eat(){ System.out.println("Learning hungry,You need to eat..."); } public void sleep(){ System.out.println("Tired of study,You need to rest..."); } } //Worker class Worker{ //Define member methods public void eat(){ System.out.println("Knock the code,You need to eat..."); } public void sleep(){ System.out.println("Knock the code and get stuck,You need to rest..."); } } //Use inherited notation: //The common contents of Student class and Worker class are extracted into Person class and human class class Person{ public void eat(){ System.out.println("Hungry,You need to eat..."); } public void sleep(){ System.out.println("Sleepy,You need to rest..."); } } //Students and workers: inherited from Person class Student extends Person{} class Worker extends Person{} //Test class public class ExtendsDemo { public static void main(String[] args) { //test Student s = new Student() ; s.eat() ; s.sleep(); System.out.println("----------------------") ; Worker worker = new Worker(); worker.eat(); worker.sleep(); System.out.println("========================================="); //Join inheritance Student s2 = new Student() ; s2.eat(); s2.sleep(); Worker w2 = new Worker() ; w2.eat(); w2.sleep(); } }
According to the above example, we can easily see the benefits of inheritance
1.2 characteristics of inheritance
I.Java Only single inheritance is supported class Zi extends Fu II.however Java Multi level inheritance clssa Fu extends Grd{} class Zi extends Fu{} //------------------------------------------------------------------------- class GrandFather{ public void method(){ System.out.println("I'm Grandpa..."); } } class Father extends GrandFather{ /* public void method(){ System.out.println("I'm grandpa "); }*/ public void show(){ System.out.println("shou Father..."); } } //Single inheritance class Son extends Father{ public void function(){ System.out.println("function son..."); } } //Multiple inheritance: not supported between classes //class Son extends Father ,Mother{ //} //Test class public class ExtendsDemo2 { public static void main(String[] args) { //Create subclass objects Son son = new Son() ; son.function(); son.show(); son.method(); * *We can see son You can use your own method,You can also use the father's method and grandpa's method. * } }
1.3 precautions for inheritance
* 1)The subclass inherits the parent class:You can inherit non private members of the parent class, * Private members are inaccessible to the outside world,Can only be accessed in this class * However, it can be accessed indirectly through public methods! * * 2)Constructors cannot be inherited,But subclasses can be passed indirectly * super Keyword to access the constructor of the parent class
class Fu{ //Non private member variable public int num = 20 ; private int num2 = 50 ; public void show(){ System.out.println(num); System.out.println(num2); System.out.println("-----------------"); String str = getStr(); System.out.println(str); } //Return String content private String getStr(){ return "hello,extends !" ; } } //Define subclasses class Zi extends Fu{ //Subclass own method public void method(){ System.out.println("method zi ..."); } } //Test class public class ExtendsDemo3 { public static void main(String[] args) { //Create subclass objects Zi zi = new Zi() ; System.out.println(zi.num) ; // System.out.println(zi.num2) ; // Private member variable System.out.println("----------------------"); //Access the show method, which is public and can be inherited by subclasses zi.show() ; zi.method(); //Access the functions of this class //zi.getStr() ;// Private member methods in the parent class //Can't call //Can only be called indirectly through public zi.show() ; } }
1.4 relationship between member variables (member methods) in inheritance
a)The subclass inherits the parent class,If the member variable name in the subclass is inconsistent with the member variable name of the parent class,Visit separately! b)The subclass inherits the parent class,If the member variable name of the child class is consistent with that of the parent class:How to access it? (a key) 1)First, find the local location of the subclass,Does the local variable name exist,If so,Just use 2)without,Find it at the member position of the subclass,Does this variable exist,If present,Just use 3)If not found in the member location of the subclass,Find directly in the member location of the parent class,If so,Is to use! 4)If there are no member positions of the parent class,There is no such variable,report errors! Follow a principle:Proximity principle! The member method calls are consistent with the object //---------------------------------------------------------------
1.5 access to construction methods in inheritance
* Access to constructor in inheritance: * * 1)The subclass inherits the parent class,All constructors of subclasses will access the parameterless method of the parent class by default * * The first sentence of all construction methods of subclasses:Hidden by default super() ; Because the number of the parent class can be used in the child class * Therefore, the parent class must be initialized first in the inheritance relationship---->Construction method : Hierarchical initialization!(Nonparametric construction method of ancestor class,stay * Construction method of execution subclass) * * super:Represents the spatial representation of the parent class object(Address value reference of parent object!) * * * 2)If the parameterless constructor in the parent class does not,What happens to subclasses? * All constructs of subclasses will report errors! (Because all construction methods of the subclass default to the parameterless construction method of the parent class!) * * *How to solve it? * Mode 1:Manually give the parameterless construction method of the parent class(recommend) * Mode 2:The first sentence in the subclass construction method:adopt super(xxx),A parameterized constructor that indirectly accesses the parent class * Mode 3:As long as one of all the construction methods of the subclass can initialize the parent class! * In the parametric construction method of subclass:this():---->Access the parameterless constructor of this class,Then it is used in the parameter free construction method of subclass * A parameterized constructor that indirectly accesses the parent class super(xxx) ; *
1.6 difference between super and this
this:Represents the address value reference of the current class object super:The address value reference of the parent class object represented by(Represents the spatial identity of the parent class) Accessing member variables this.Variable name; Access the member variables in this class super.Variable name; Accessed is the member variable of the parent class Access construction method: this() ; Access the parameterless constructor of this class super() ;The parameterless constructor of the parent class accessed this(xxx);Access the parameterized constructor of this class super(xxx);The parameterized constructor of the parent class being accessed Member method: this.Method name();The member methods of this class are accessed super.Method name() ;The member method of the parent class is accessed
1.7 initialization and code block priority issues
* 1)Initialization of inheritance: * Hierarchical initialization:Let the parent class initialize first,Then subclass initialization * 2)Priority of code block * Static related execution first:Static code blocks are executed first,Just once!!! * Load as class loads,Execute only once * Static code block > Construct code block > Construction method
1.7.1 code block classification
Code block * * stay Java in,use{}Wrapped content,Become a code block! * * classification: * Local code block :Use in method definitions ,effect:Define the life cycle of a local variable * Construct code block:At the member location of the class(In class,Outside method),use{}Wrap it up:Data initialization for some members in the class * characteristic:Every time before executing the construction method,If a construction code block exists,Execute the content in the construction code block first! * * Static code block: * At the member location of the class,Direct use static{},characteristic:Loads as the class loads,Prior to object existence!
class Code { //Static code block static{ int x = 1000; System.out.println(x); } //Nonparametric construction method public Code(){ System.out.println("code demo..."); } //Construct code block { int x = 100 ; System.out.println(x); } { int y = 200 ; System.out.println(y); } //Parametric construction method public Code(String name){ System.out.println("code demo"+name); } //Static code block static{ int y = 2000 ; System.out.println(y); } } //Test class public class CodeDemo { public static void main(String[] args) { //Define a variable // int a = 10 ; // System.out.println(a); //Define a local code block { int x = 20 ; System.out.println(x); //The scope of x is valid within {} } // System.out.println(x); //Create a Code class object Code code = new Code() ; System.out.println("-----------"); Code code2 = new Code("hello") ; } }
1.8 timing of succession
Do not inherit for partial functionality,Maybe you can inherit the functions you don't need. Inheritance has limitations The correct use of inheritance relationship should be A yes B Class,You can then use inheritance relationships The real world embodiment of inheritance relationship is a kind of "is a"Relationship
2. Method rewriting (the premise of polymorphism)
If a subclass as like as two peas is declared, it is called method rewriting. (Override) - Method replication (Override)
Format:
* Permission modifier return value type method name(parameter list){ * ... * } * tips:The permission modifier level cannot be lower than the parent method!!!!!!!!!!!
2.1 difference between method rewriting and method overloading
The difference between method rewriting and method overloading? * * Method overloading: In a class,provide n Multiple functions,These functions,Same method name,The parameter list is different,Independent of return value(objective:Improve the scalability of a function) * The parameter list is different: * 1)Different types * 2)Different number * 3)Consider the order of parameter types * * public static void open(int a,double d){} * public static void open(double a,int b){} * Construction methods can also be overloaded!(In the same category) * public Demo(){} public Demo(int a){} * * Method rewrite: In inheritance,Subclass as like as two peas in the same parent class,Purpose of rewriting:Subclasses have their own functions,You need to override this function of the parent class! *
3. Polymorphism
Different forms of a thing
Object changes in memory
3.1 prerequisites for polymorphism
* 1)Inheritance relationship must exist (extends) * 2)Method overrides must exist * The subclass needs to override the function of the parent class * Animal * eat():"Animals need to eat..." * Cat * eat() "Cats eat fish" * Dog * eat() "Dogs eat bones" * * 3)A parent class reference must point to a child class object * class Fu{} * class Zi extends Fu{ * //Existence override * } * * format: Fu fu = new Zi() ; *
3.2 benefits of polymorphism
1.Improve code reusability(Guaranteed by inheritance) 2.It improves the scalability of the code A parent class reference points to a child class Fu fu = new zi
3.3 polymorphic member access characteristics
* * 1)Access problems for member variables: * Compile look left,Run left!(Use father's things) * 2)Aiming at the access problem of member methods in polymorphism: What we call member variables/Member method----wrong static * Compile look left,Run right(Because the subclass overrides the parent class) * 3)If the member method is static:(Static member methods are not method overrides,You can access it directly by class name,Class related methods) * Compile look left,Run left * 4)Construction method: * There is an inheritance relationship: You also need to let the parent class initialize first,Then initialize the subclass!(Hierarchical initialization!)
3.4 disadvantages of polymorphism
Cannot access subclass specific functions
Fu fu = new zi
fu. The method name reported an error. There is no such method in Fu
So how to solve the disadvantages?
Use downward transformation
Point the parent class reference to the child class,Convert to subclass reference Fu fu = new zi Zi zi = (Zi) fu zi.Method name()You can call the specific functions of the subclass And there is no need to open up new space in the heap
4. Interface
Extended function of interface real world things
Whoever accesses the interface has this function
Interface definition format
interface Interface name {}
4.1 characteristics of interface
1.No constructor in interface 2.Default constants for members in interface 3.Member methods in an interface can only be abstract methods(No method body) Interfaces cannot be instantiated,Class instantiation can only be implemented through concrete classes-----Interface polymorphism
4.2 interface and relationship between classes
Between classes Inheritance relationship extends Only single inheritance is supported, but multi-level inheritance is allowed Between class and interface Implementation relationship implements Class can implement multiple interfaces while inheriting,Interfaces are separated by commas Interface to interface Inheritance relationship extends Only single inheritance is supported,You can also separate multiple inheritance with commas
4.3 instance of
It belongs to a binary operation symbol
It is used to compare whether the object on the left is an instance of the object on the right
abstract class Animal{ public Animal() { } public abstract void eat() ; } class Dog extends Animal{ public Dog() { } @Override public void eat() { System.out.println("Dogs eat bones"); } } class Cat extends Animal{ @Override public void eat() { System.out.println("Cats eat fish"); } } class Pig extends Animal{ @Override public void eat() { System.out.println("Pigs eat cabbage..."); } } //Test class public class Test3 { public static void main(String[] args) { Animal a = new Dog() ; a = new Pig() ; //if statement if(a instanceof Dog){ System.out.println("Is an instance of the dog type"); }else if(a instanceof Cat){ System.out.println("Is an instance of the cat type"); }else if(a instanceof Pig){ System.out.println("This is an example of a pig type"); }else{ System.out.println("I'm sorry,No current instance..."); } } }
2, Some common keywords
1. Static
If there is an attribute that everyone has the same, repeated definitions consume too much memory
Java provides Keywords: static: the most basic concepts: sharing, sharing
Add static to the variable
The static modified variable is a class variable, which takes precedence over the member variable loading, and has been put into memory when the class is loaded
** * static state static Characteristics of keywords: * * 1)Loads as the class loads * * 2)Prior to object existence: It can't this coexistence (this:Represents the address value reference of the current class object) * Object not yet new When,Currently being static The modified member is already in memory * * 3)Statically decorated objects can be shared by multiple objects:It means sharing * * give an example: * Water in water dispenser(fit) * Cup sharing(unsuited!) * * 4)Statically decorated variables,method----->Static variable or static method * What we call member variables and member methods:All refer to non static * * Access mode of static members:Class name.variable * * Class name.Method name() * */
Tips: * precautions for using static keyword
1) Non static methods can access both static and non static variables
You can call either static or non static methods
2) Static methods: only static variables can be accessed,
Only static methods can be called
2.final
* about final Characteristics of keywords: * 1)Can modify class,This class cannot be inherited! * 2)Modifier member methods can be used,Member methods cannot be overridden! (According to the specific requirements of the topic!) * 3)Variables that can be modified,This variable is now a constant! (Custom constant) * * final Modifies the difference between basic data type and reference type? * * final Modify basic data type: The corresponding data value of the basic data type cannot be assigned,Can only be assigned once! * final Decorated reference type:The address value corresponding to the reference data type cannot be changed * final Student s = new Student() ;//Modify the instance variable s, and the heap memory address value of S is always a fixed value! * s = new Student() ;//Reopen space (error report) * *
3. Abstract
abstract can be used to modify methods and classes
Become abstract methods and abstract classes
abstract class{}
abstract void xxx();
3.1 characteristics of abstract classes
1.A class with abstract methods must be an abstract class 2.There are not only abstract methods in abstract classes,There can also be non abstract methods 3.Abstract classes cannot be instantiated(Objects cannot be created directly)-----Abstract class polymorphism It can be indirectly instantiated through subclasses:A parent class reference points to a child class 4.Subclasses of abstract classes can be abstract classes or concrete subclasses But if the subclass is an abstract class, it makes no sense,Unless there are subclasses that are concrete subclasses 5.Abstract classes have construction methods,For hierarchical initialization The core tenet of abstract classes:Is to force subclasses to do what they have to do(All abstract methods in the parent class must be overridden,Otherwise, an error is reported!)
3.2 what keywords conflict with
private conflict: Private method,Can only be accessed in this class,join abstract The destination needs to be overridden by subclasses,The function of subclass needs to be called! static conflict: Static methods load as the class loads,Static method---Not a rewrite,So its access By class name.Method name()---->Abstract methods have no method body final conflict cover final Decorated member methods cannot be overridden,And join abstract The method needs to be overridden!
4. Permission modifier
Default modifier Private modifier:private Protected:protected Public,Open:public In this category In subclasses under the same package/In unrelated classes In subclasses of different packages In unrelated classes under different packages private √ Default modifier √ √ protected √ √ √ public √ √ √ √ * * Modify permissions from small to:private,default,protected,public *
3, Methodological issues
1. The parameter is a reference data type (except String)
In the second week, the formal parameters of the method are mentioned, which are supplemented here
If the formal parameter of the method is a class When calling a method,How to pass actual parameters? concrete class,Call this method,The actual parameter needs to pass the object of the current concrete class abstract class,The subclass object of the abstract class that needs to be passed to call the actual parameters of the method (Abstract class polymorphism) The formal parameter is interface,Call this method,The actual parameters need to be passed are the sub implementation class objects of the current interface(Interface polymorphism) common ground:You always need to pass in a concrete instance,Operation method
2. Return value of method
If the return value of a method is a reference type and the final method ends, how to return?
* class * concrete class:Method returns the current concrete class object! * abstract class:What needs to be returned is the subclass object of the abstract class * * Interface:What needs to be returned is the sub implementation class object of the interface * *The return value of a method call must be the object acceptance of the implementation class
For example, the return value of a method is an interface
interface Mary{ public abstract void mary() ; } //MaryDemo class class MaryDemo{ public Mary function(){//The return value type is the interface type, // Mary mary = new Mary() ; // Interface cannot be instantiated //Subclass objects that need to provide interfaces //Interface polymorphism // Mary mary = new You() ; // return mary ; //One step return new You() ; } } //Define a class class You implements Mary{ @Override public void mary() { System.out.println("Get married,Very happy..."); } } //Test class public class LoveTest { public static void main(String[] args) { //Call the function method in the MaryDemo class? MaryDemo maryDemo = new MaryDemo() ; Mary mary = maryDemo.function(); mary.mary(); System.out.println("----------------------"); //Anonymous object Mary m = new MaryDemo().function(); m.mary(); } }
4, Inner class
You can define another class in one class
For example, a class B is defined in class A
Then B is the inner class of A
1. What are the benefits of using internal classes
-
1) Realize multiple inheritance;
-
2) Internal classes can be well hidden: general non internal classes are not allowed to have private and protected permissions, but internal classes can
-
3) It reduces the size of bytecode file generated after class file compilation
2. Types of internal classes
Member inner class, static inner class, local inner class, anonymous inner class
3. Characteristics of internal classes
The internal class can access the member variables of the external class, including private variables!
It can be regarded as the same class, and private variables can be accessed naturally
External classes need to access internal class member methods
Prerequisite inner classes cannot be statically decorated
Outer2.Inner2 oi = new Outer2().new Inner2() ; oi.Method name
If the inner class is static, how to access the members of the inner class directly?
* The static member inner class is regarded as the static member access of the outer class * * Direct access * External class name.Internal class name object name = new External class name.Internal class name() ;
class Outer3{ //Define non static member variables public int num = 50 ; private static int num2 = 20 ; //Define member inner class: static ----- > static member inner class can be regarded as static member of external class static class Inner3{//At this time, all classes are static public void show(){ // System.out.println(num); System.out.println(num2); } public static void show2(){ // System.out.println(num); System.out.println(num2); } } } //Test class public class InnerClassDemo3 { public static void main(String[] args) { // External class name Internal class name object name = external class object Internal class objects; //Outer3.Inner3 oi = new Outer3().new Inner3() ; It doesn't work anymore // External class name Internal class name object name = new external class name Internal class name (); Outer3.Inner3 oi = new Outer3.Inner3() ; oi.show(); oi.show2() ; //Static -- object name access is not recommended System.out.println("------------------------------"); //Another way of show2() Outer3.Inner3.show2(); //show2() static method } }