3.1.1 customized package
If the package is not declared in the program, the class will be stored in the default package, which is not advocated.
Syntax:
package Package name
Package naming conventions:
- The naming specification of the package should reflect the good division of project resources
- Naming specification of the package where the custom label class is located: company name Name of development team entry name
For example: com java. explorer
The statement declaring a package must be written on the first line of the class
3.1.2 import of package
Syntax:
import Package name.Class name
Example:
import java.util.*; //Import Java All classes in util package import java.util.ArrayList; //Import Java ArrayList class in util package
Example: use the Tree class in the Hero class. The Hero class is not in the same package as the Tree class
package com.java.oriented.dota.scene; public class Tree { public void clear(){ //Specific business logic } } package com.java.oriented.dota.figure; //Since the Tree class and Hero class are not in the same package, you need to use the import keyword to import the package import com.java.oriented.dota.scene.Tree; public class Hero { public void eatTree(Tree tree){ //Call the clear() method of the tree object, and the eaten tree disappears in the map tree.clear(); } }
3.1.3 access rights of package
Members with default access rights in a package can only be referenced in the same package.
If the access permission of members in a package is public, these members can be referenced by classes in other packages.
The above "members" refer specifically to classes, properties and methods.
Public members can be accessed by classes in other packages, and protected members in public classes can be accessed by subclasses derived from them in other packages.
package com.java.oriented.dota.scene; public class Tree { void clear(){ //Remove public //Specific business logic } } package com.java.oriented.dota.figure; //Since the Tree class and Hero class are not in the same package, you need to use the import keyword to import the package import com.java.oriented.dota.scene.Tree; public class Hero { public void eatTree(Tree tree){ //Call the clear() method of the tree object, and the eaten tree disappears in the map tree.clear(); } }
3.2 succession
Inheritance is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes.
Inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class.
Inheritance in life:
3.2.1 overview of inheritance
- Inheritance is an important feature of object-oriented programming. It derives subclasses by inheriting the original classes, and then constructs more complex subclasses.
- Subclasses not only have the newly defined behavior characteristics, but also inherit the behavior characteristics of the original class.
- Parent and child classes have the relationship of inclusion and inclusion, which is an is-a relationship.
- In Java, inheritance can extend functions on the basis of existing classes, so that new classes can be developed more quickly, so that new classes can not only reuse the characteristics and behaviors of the current class, but also define their own characteristics and behaviors.
- Inheritance can greatly improve the reusability of code, reduce the amount of code and facilitate the later maintenance of the program.
Java inheritance syntax:
[Modifier ] class Subclass name extends Parent class name{ //Class definition part }
A parent class is also called a base class or superclass
3.2.2 implementation of inheritance
. example: define parent weapons, and subclasses sword and spear
public class Weapon { //Parent class: Weapon String name;//Weapon name int attackValue;//Attack value //Construction method public Weapon(String name, int attackValue) { System.out.println("--Execute weapon parent Weapon Construction method of--"); this.name = name; this.attackValue = attackValue; } //Attack method public void attack(){ System.out.println("Weapon name:"+name+"\t"+"attack value:"+attackValue); } } public class Sword extends Weapon{ //Holy sword subclass public Sword(String name, int attackValue) { super(name, attackValue); } } public class Spear extends Weapon{ //Holy sword and spear //Construction method public Spear(String name,int attackValue) { super(name, attackValue); } } public class ExtendsTest { // Test class public static void main(String[] args){ Sword word = new Sword("Holy sword",300); word.attack(); Spear spear = new Spear("Spear",250); spear.attack(); } }
3.3 overloading and rewriting
3.3.1 heavy load
Rules for method overloading:
Method names must be the same.
The parameter list must be different (different number, different type, different order of parameters, etc.).
The return types of methods can be the same or different.
Just because the return type is different is not enough to be a method overload.
be careful:
Different parameter lists include different numbers, types and orders.
It is not allowed to only have different parameter variable names.
Like member methods, constructor methods (constructors) can also be overloaded.
Methods declared final cannot be overloaded.
Methods declared as static cannot be overloaded, but can be declared again.
Example: define three mutually overloaded methods in the Book class, which calculate the price of books in different situations.
public class Book { //Define 3 overloaded methods public float getPrice(){ return 100; } public float getPrice(int page){ return (float)(page*0.1); } public float getPrice(int page ,float discount){ return (float) (page*discount); } public static void main(String[] args) { Book book=new Book();//Create a Book Object System.out.println("default Book price:"+book.getPrice()); System.out.println("Calculate the book price according to the number of pages:"+book.getPrice(268)); System.out.println("Calculate the book grid according to the number of pages and discount:"+book.getPrice(360,0.2f)); } }
3.3.2 rewriting
In the subclass, you can override the methods inherited from the parent class as needed.
The overridden method and the overridden method must have the same method name, parameter list, and return type. Rewriting methods cannot use more stringent access rights than the method being rewritten.
An overridden method cannot declare an exception type that throws a larger range than the overridden method.
Rewriting is that the shell remains unchanged and the core changes. In other words, the method name remains unchanged, the parameters remain unchanged, and the specific implementation can be changed. Methods are generally declared in the parent class and overridden in the child class. Overloading means that the method name remains unchanged, but the parameters must be changed. And overloaded methods are usually written in a class.
Reminder:
Override is a change made by a subclass to the same method of the inherited parent class. This change needs to follow the format of the parent class.
The access rights of subclass rewriting methods, throwing exceptions, etc. need to be within the control scope of parent methods, but their internal specific implementation can be different.
The return value of the subclass override method can be the subtype of the return value of the overridden method in the parent class; If method parameters are subclass types, they are overloaded rather than overridden.
Example: override the flying method of the parent bird in the child ostrich
public class Bird { // Parent birds //fly() method of Bird class public void fly(){ System.out.println("I fly freely in the blue sky and white clouds..."); } } public class Ostrich extends Bird{// Subclass ostrich public void fly(){ //Override parent method System.out.println("I can only flap my wings and run on land..."); } public void prey(){ //Predation method fly(); System.out.println("Execute predation method"); } public static void main(String[] args) { Ostrich ostrich=new Ostrich(); ostrich.prey(); //Call pre() of ostrich object } }
3.3.3 rewrite coverage problem
If you need to access the method overridden by the subclass, you can use the super keyword to indicate the instance method that calls the parent class overridden.
Example: when the child ostrich preys, it will use the flying function of the parent bird.
public class Ostrich extends Bird{ public void fly(){ System.out.println("I can only flap my wings and run on land..."); } //Predation method public void prey(){ //Use the super key in the pre () method to call the fly() method of the parent class super.fly(); System.out.println("Execute predation method"); } public static void main(String[] args) { //Create Ostrich object Ostrich ostrich=new Ostrich(); ostrich.prey();//Call fly() of ostrich object } }
3.4 polymorphism
- From a certain point of view, encapsulation and inheritance are almost always prepared for polymorphism.
- Polymorphism means that different kinds of objects are allowed to respond to the same message. That is, the same message can adopt many different behavior modes according to different sending objects.
- Polymorphism means that the same operation acts on different objects, can have different interpretations and produce different execution results.
- At compile time, you can point to the subclass object through the reference of the parent class. At run time, you can call the method of overriding the parent class in the subclass through the subclass object pointed to by the parent class.
3.4.1 polymorphic application
Example: the polymorphism reflected by the parent class reference pointing to the subclass when executing the override method
//Parent character public class Figure { protected String name; public void attack(){ //There is no specific attack operation here. Heroes of different classes have different attack methods } public void run(){ System.out.println("Running"); } } //Subclass Warrior public class Warrior extends Figure{ //Override the attack() method of the parent class public void attack(){ System.out.println(this.name+"Physical attack in progress......"); } } //Subclass mage public class Master extends Figure { //Override the attack() method of the parent class public void attack(){ System.out.println(this.name+"Under magic attack......"); } public static void main(String[] args) { Figure master=new Master(); master.name="Demon Wizard"; Figure warrior=new Warrior(); warrior.name="Earth shaking cow"; master.attack(); warrior.attack(); } }
3.4.2 cast of reference variable
Example: the method calling the parent class reference is not defined in the parent class
//Subclass mage public class Master extends Figure { //Override the attack() method of the parent class public void attack(){ System.out.println(this.name+"Under magic attack......"); } //Special bombing function of subclass public void bomb(){ System.out.println(this.name+"It's being magically bombed......"); } public static void main(String[] args) { Figure figure=new Master(); figure.name="Demon Wizard"; figure.attack(); figure.bomb(); //Error compiling here } }
analysis:
A reference variable can only call a method of its compile time type, not a method of its runtime type, that is, {so that the actual referenced object does contain the method.
If you need a reference variable to call a method of a runtime type, you must cast it to a runtime type with the help of a type conversion operator.
3.4.3 instance of operator
The instance of operator is used to determine whether an instance is an instance of a class
Syntax:
a instanceof A Judgment example a Is it a class A If true, return true,Otherwise return false.
//Subclass mage public class Master extends Figure { //Override the attack() method of the parent class public void attack(){ System.out.println(this.name+"Under magic attack......"); } //Special bombing function of subclass public void bomb(){ System.out.println(this.name+"It's being magically bombed......"); } public static void mafigurein(String[] args) { Figure figure=new Master(); figure.name="Demon Wizard"; figure.attack(); if(figure instanceof Master ) Master master = (Master)figure; // Use downcast master.bomb(); //Successfully called the bob of Master class } }
3.4.4 practice
Summary:
The statement declaring the package is "package} package name", which must be placed on the first line, and the statement importing the class is "import package name. Class name".
Inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class.
The syntax of the subclass inheriting the parent class is: "[modifier] class subclass name" extends "parent class name".
Overloading means that multiple methods can be created in a class. They have the same name, but different parameters and different definitions.
Rewriting is to rewrite the parent method in the subclass method. The rewritten method and the rewritten method must have the same method name and parameters
List and return type.
Polymorphism means that the same operation acts on different objects, can have different interpretations and produce different execution results.
At compile time, you can point to the subclass object through the reference of the parent class. At run time, you can call the method of overriding the parent class in the subclass through the subclass object pointed to by the parent class.