static keyword
Features of static keyword:
1) Loads as the class loads
2) Priority object exists:
It cannot coexist with this (this: represents the address value reference of the current class object)
When the object does not have new, the member currently modified by static has memory
3) Statically modified
Can be shared by multiple objects: it means sharing
Example: water in water dispenser (suitable) < = = > water cup sharing (not suitable!)
4) Statically modified variable, method = > static variable or static method
By member variables and member methods, we mean non static
Static member access method: class name Variable \ class name Method name ()
5) Precautions for using static keyword:
① Non static methods can access both static and non static variables; You can call either static or non static methods
② Static methods: only static variables can be accessed; Only static methods can be called
Static access only: simple
The difference between static variables and member variables
Belong to different
Static variables belong to classes, so they are also called class variables
Member variables belong to objects, so they are also called instance variables (object variables)
Different locations in memory
Static variables are stored in the static area of the method area
Member variables are stored in heap memory
Memory appears at different times
Static variables are loaded with the loading of the class and disappear with the disappearance of the class
Member variables exist with the creation of the object and disappear with the disappearance of the object
Call different
Static variables can be called by class name or object
Member variables can only be called by object name
Code block
In Java, the content wrapped with {} becomes a code block!
Classification of code blocks
Local code block: used in method definition to limit the life cycle of local variables
Construct code block: use {} wrapping at the member position of the class (in the class, outside the method): initialize some members of the class
Characteristics of code blocks
Each time before executing the construction method, if there is a construction code block, execute the content in the construction code block first
Static code block
In the member position of the class, use static {} directly,
characteristic:
With the loading of the class, it takes precedence over the existence of the object!
effect:
You can also use the static code block to perform some operations (create a file. JDBC (Java link database registration driver) for the later I0 stream)
Static code blocks are loaded once!
Priority:
Static code block > construction code block > construction method
eg.
package HemoWork.day10; public class Test01 { public static void main(String[] args) { new Leaf(); } } class Root { static { System.out.println("Root Static initialization block for"); } { System.out.println("Root Normal initialization block"); } public Root() { System.out.println("Root Parameterless constructor for"); } } class Mid extends Root { static { System.out.println("Mid Static initialization block for"); } { System.out.println("Mid Normal initialization block"); } public Mid() { System.out.println("Mid Parameterless constructor for"); } public Mid(String msg) { this(); System.out.println("Mid A constructor with parameters, whose parameter values are:" + msg); } } class Leaf extends Mid { static { System.out.println("Leaf Static initialization block for"); } { System.out.println("Leaf Normal initialization block"); } public Leaf() { super("hello"); System.out.println("Leaf Constructor for"); } }
Operation results:
Root Static initialization block for Mid Static initialization block for Leaf Static initialization block for Root Normal initialization block Root Parameterless constructor for Mid Normal initialization block Mid Parameterless constructor for Mid A constructor with parameters, whose parameter values are: hello Leaf Normal initialization block Leaf Constructor for
inherit
Concept of inheritance:
The common contents of multiple classes are extracted into independent classes, and then these classes have a relationship with independent classes: inheritance relationship
Benefits of inheritance:
1) Improve code maintainability
2) Improve code reusability
3) It is "the precondition of polymorphism" to create a relationship between classes
When to use inheritance?
1) Do not use inheritance relationships for partial functionality
2) Inheritance can be used when A is a B
Characteristics of inheritance:
1) Inheritance only supports single inheritance. Some languages support multiple inheritance, but Java does not
2) Multi inheritance is not supported, but multi-level inheritance is supported
matters needing attention:
1) Subclass inherits from parent class: you can inherit non private members of the parent class. Private members cannot be accessed from the outside world, but only in this class. However, indirect methods can be accessed through public access
2) Constructors cannot be inherited, but subclasses can introduce the constructors that access the parent class through the super keyword
Relationship between member variables:
a) The subclass inherits from the parent class. If the member variable name in the subclass is inconsistent with the member variable name of the parent class, you can access it separately!
b) The subclass inherits from the parent class. If the member variable name of the subclass is the same as that of the parent class, how to access it?
1) First, find out whether there is a local variable name at the local position of the subclass. If so, use
2) If not, find out whether this variable exists at the member position of the subclass. If so, use
3) If it is not found in the member position of the child class, it is directly found in the member position of the parent class. If it is found, it is used!
4) If there is no member position of the parent class, there is no variable. An error is reported!
Follow a principle: the principle of proximity!
Access to parameterless constructor in inheritance:
1) The subclass inherits from the parent class, and all construction methods of the subclass will access the parameterless method of the parent class by default
2) What happens if there is no parameterless construction method in the parent class?
All constructions of subclasses will report errors! (because all constructors of the subclass default to the parameterless constructors of the parent class!)
How to solve it?
Method 1: manually give the parameterless construction method of the parent class (recommended)
Method 2: the first sentence in the subclass construction method: indirectly access the parameterized construction method of the parent class through super (xxx)
Method 3: as long as one of all the construction methods of the subclass can initialize the parent class!
The difference between method overloading and method Rewriting:
Method overload:
In a class, n multiple interfaces are provided. These functions have the same method name, different parameter lists and have nothing to do with the return value (purpose: to improve the scalability of a function)
Different parameter lists: ① different types, ② different numbers, ③ consider the order of parameter types
Construction methods can also be overloaded
Method override:
In inheritance relations, as like as two peas, the subclass is identical to the parent class. The method declaration is for rewriting purposes: the subclass has its own function and needs to cover the function of the father.
When overriding methods, you should pay attention to:
When the current subclass inherits from the parent class, if there is a method override, the subclass cannot override the method with lower access rights
Either keep consistent with the parent method or add public, preferably the same as the modification of the parent
When to use inheritance
If class A is a kind of class B, or class B is a kind of class A, this uses extensions to complete the continuous relationship between the two, which reflects a "is a" relationship. Don't use inheritance for some functions!
eg.
public class People { private String name; private int age; private String sex; public People() { } public People(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public void eat() { } } class PeopleNan extends People { public PeopleNan() { } public PeopleNan(String name, int age, String sex) { super(name, age, sex); } @Override public void eat() { System.out.println("Southerners eat rice"); } public String work() { return "Southerners do business"; } } class PeopleBei extends People { public PeopleBei() { } public PeopleBei(String name, int age, String sex) { super(name, age, sex); } @Override public void eat() { System.out.println("Northerners eat noodles"); } public String work() { return "Northern entrance examination"; } } class PeopleTest { public static void main(String[] args) { People people = new People(); PeopleBei peopleBei = new PeopleBei(); PeopleNan peopleNan = new PeopleNan(); peopleBei.setName("Laobei"); peopleBei.setAge(40); peopleBei.setSex("male"); System.out.println("I am" + peopleBei.getName() + ",this year" + peopleBei.getAge() + ",It's a" + peopleBei.getSex()+"of"); peopleBei.eat(); System.out.println(peopleBei.work()); peopleNan.setName("Nanjie"); peopleNan.setAge(40); peopleNan.setSex("female"); System.out.println("I am" + peopleNan.getName() + ",this year" + peopleNan.getAge() + ",It's a" + peopleNan.getSex()+"of"); peopleNan.eat(); System.out.println(peopleNan.work()); } }
Operation results:
I'm Lao Bei, 40 this year,It's a man Northerners eat noodles Northern entrance examination I'm sister Nan. I'm 40 this year,It's a woman Southerners eat rice Southerners do business
eg2
public 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 String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void eat(){} public void play(){} public void introduce(){ System.out.println("I am a"+getName()+",I am"+getColor()+"Color, this year"+getAge()+"year"); } } class Cat extends Animal{ public Cat() {} public Cat(String name, int age, String color) { super(name, age, color); } public void eat(){ System.out.println("Cats eat"); } public void play(){ System.out.println("The cat licked itself"); } public void introduce(){ System.out.println("I am a"+getName()+"Cat, I am"+getColor()+"Color, this year"+getAge()+"year"); } } class Dog extends Animal{ public Dog() { } public Dog(String name, int age, String color) { super(name, age, color); } public void eat(){ System.out.println("Dog eat"); } public void play(){ System.out.println("Dogs eat bones"); } public void introduce(){ System.out.println("I am a"+getName()+"Dog, I am"+getColor()+"Color, this year"+getAge()+"year"); } } class AnimalTest{ public static void main(String[] args) { Animal animal = new Animal(); Cat cat = new Cat("chinese rhubarb",3,"yellow"); Dog dog = new Dog("Big hair",5,"white"); cat.eat(); dog.eat(); cat.play(); dog.play(); cat.introduce(); dog.introduce(); } }
Operation results:
Cats eat Dog eat The cat licked itself Dogs eat bones I'm a big yellow cat. I'm yellow. I'm 3 years old I'm a big haired dog. I'm white. I'm 5 years old
super and this keywords
This represents the reference corresponding to this class.
super represents the identification of the storage space of the parent class (which can be understood as a parent class reference)
final keyword
Features of final keyword:
1) This class can not be inherited!
2) Modifier member methods can be used. Member methods cannot be overridden! (according to the specific requirements of the topic!)
3) Variable that can be modified. This variable is a constant at this time! (custom constant)
Interview questions:
Final, finally, finalize?
Keyword description of final and its three characteristics
finally: it is often used to try... catch... finally (later)
finalize(): related to garbage collector: Reclaim objects without more references in memory (common classes will be discussed later)
Variables modified by final:
Common variables:
final int a = 10;
Instance variable:
final Student student = new Student();
fina1 modifies the difference between basic data type and reference type?
final modifies the basic data type: the corresponding data value of the basic data type cannot be assigned, but can only be assigned once!
final modify 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! new Student() ;//Reopen space (error report)
Constant written in development:
Both use public static final int a = 100;
public: the access permission is large enough
static: can be accessed directly by the class name
final: this variable is a constant
polymorphic
Concept of polymorphism
A thing has different forms at different times
Prerequisites for polymorphism
1) The inheritance relationship extends must exist
2) There must be a method override [the subclass needs to override the function of the parent class]
3) A parent class reference must point to a child class object (transition up)
F f = new Z();
Polymorphic access characteristics
1) Access problems for member variables
Compile to the left (see if there are variables in the Fu class. If there are variables, the compilation will not report errors!)
Run to the left (something using the Fu class)
2) Access problems for member methods (non static)
Compile to the left (see whether this method exists in Fu class. If it exists, the compilation will not report an error!)
Run to the right (there is a method override, so the function of the final subclass overrides the function of the parent class!)
3) If the member method is a static method (the static member method is not a method override, it can be accessed directly by the class name, and the method related to the class)
Compile to the left (see if this static method exists in the Fu class. If it exists, the compilation will not report an error!),
Run left (static as like as two peas): subclass has static mode of parent class, not rewrite, and class related.
4) Access problems for construction methods:
There is an inheritance relationship: the parent class needs to be initialized first, and then the child class needs to be initialized! (hierarchical initialization!)
Benefits of polymorphism
1) Improved code reusability (with inheritance guarantee)
2) Improved code extensibility (with polymorphism guarantee)
Disadvantages of polymorphism
Cannot access subclass specific functions
How to solve it? (how to access functions unique to subclasses)
Scheme 1: create specific subclass objects for specific subclasses
Zi z = new Zi() ; z.Member's legal name() itself Fu f = new Zi();//Space has been made in heap memory Zi z = new Zi();//It also opens up space in heap memory. From the perspective of memory, this comparison consumes memory space
Scheme 2: convert parent class reference to child class reference (downward transformation)
Fu fu = new Zi(); Zi zi = (Zi)fu;
Note:
If the downward transformation is not used properly, Java lang. ClassCastException; Class conversion exception; Is a runtime exception.
Problems will occur when the instance in the current heap memory is not of this type!
eg
class Animal{ static String name = "dog"; int age = 5; public Animal() { } public void eat(){ System.out.println("Eat when you're hungry"); } } class Dog1 extends Animal{ String name; int age = 2; public Dog1() { } public Dog1(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void eat() { System.out.println("Dogs eat bones"); } public void sleep() { System.out.println("The dog snored"); } } public class DuoTaiTest { public static void main(String[] args) { Animal animal = new Dog1("chinese rhubarb"); //Member method animal.eat();//Subclass //Cast (downcast) Dog1 dog2 = (Dog1)animal; dog2.sleep(); //Member variable int age = animal .age; System.out.println(age);//Parent class //Construction method //Assignment requires downward transformation System.out.println(((Dog1) animal).getName()); Animal dog = new Dog1("aa"); System.out.println(dog.name); } }
Operation results
Dogs eat bones The dog snored 5 chinese rhubarb dog
eg2
public class JuiceMachineTest { public static void main(String[] args) { JuiceMachine juiceMachine = new JuiceMachine(); juiceMachine.makeJuice(new Apple()); juiceMachine.makeJuice(new Banana()); juiceMachine.makeJuice(new Orange()); } } class JuiceMachine { public void makeJuice(Fruit fruit) { fruit.Juice(); } } class Fruit { public void Juice() { System.out.println("Juice!"); } } class Apple extends Fruit { public void Juice() { System.out.println("Outflow of apple juice"); } } class Banana extends Fruit { public void Juice() { System.out.println("Banana jam"); } } class Orange extends Fruit { public void Juice() { System.out.println("Outflow of orange juice"); } }
Operation results
Outflow of apple juice Banana jam Outflow of orange juice
abstract class
What is an abstract class?
In the real world, something is more general and described as an abstract thing
Some functions in a transaction can only be declared without method body.
Abstract class keyword: abstract keyword
Format of abstract method:
Permission modifier(eg.pub1ic) abstract Return value type method name (Formal parameter list); abstract class Class name{}
Characteristics of abstract classes:
1) Classes with abstract methods must be abstract classes;
2) Abstract classes do not necessarily have only abstract methods, but also non abstract methods (with method bodies);
3) Abstract class cannot be instantiated = > object cannot be created
Instantiate (create objects) through specific subclasses, and the abstract class is polymorphic Fu fu = new Zi();
4) There are two situations for subclasses of abstract classes:
① For now: if the subclasses of an abstract class are all abstract classes - it makes no sense. Because subclasses cannot be new unless there are specific subclasses;
② The subclass of an abstract class is a concrete class - can new: Abstract polymorphic form Fu fu = new Zi()
Characteristics of abstract class members:
Member method:
It can be defined as either an abstract method or a non abstract method
Member variables:
You can define either variables or constants
Construction method:
It can be a paparazzi with or without parameters
abstract keyword conflicts with those keywords:
Final: after the class modified by abstract inherits, the methods of the class need to be rewritten, while the class modified by final cannot inherit or have subclasses, and the methods cannot be rewritten, which conflicts with each other.
Private: the method of a private method subclass cannot be inherited, so it cannot be overridden. abstract is to override the method. Conflict with each other.
Static: static can be instantiated and called directly. abstract cannot be instantiated and conflicts with each other.
Interview questions:
If there is no abstract method in a class, what is the significance of defining this class as an abstract class?
In order not to instantiate it directly!
How to instantiate?
1) Directly with concrete subclasses
2) Indirect has concrete subclasses
Possible: the return value of a function is itself ----- > the logic in the function may be the most specific subclass of new!
eg
//Create a class named Vehicle and declare it as an abstract class. Declare a noofwheel method in the Vehicle class to return a string value public abstract class Vehicle { public abstract String NoOfWheels(); } //Motorbike class public class Motorbike extends Vehicle{ @Override public String NoOfWheels() { return "two-wheeler"; } } //Car class public class Car extends Vehicle { @Override public String NoOfWheels() { return "Four wheeled vehicle"; } } //Create a class with main method, and create instances of Car and Motorbike in this class, public class VehicleTest { public static void main(String[] args) { Vehicle vehicle1 = new Car(); System.out.println(vehicle1.NoOfWheels()); Vehicle vehicle2 = new Motorbike(); System.out.println(vehicle2.NoOfWheels()); } }
Operation results
Four wheeled vehicle two-wheeler
eg.2
public abstract class Animal{ String name; int age; String sex; public Animal() { } public Animal(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public abstract void eat(); public abstract void sleep(); public abstract void hobit(); public void introduce(){ System.out.println("I am"+getName()+",I this year"+getAge()+"Years old, I am"+getSex()+"of"); } } //Cats public class Cat extends Animal { public Cat() { } public Cat(String name, int age, String sex) { super(name, age, sex); } @Override public void eat() { System.out.println("Cats eat fish"); } @Override public void sleep() { System.out.println("Cat sleep"); } @Override public void hobit() { System.out.println("Cats play with wool"); } } //Dogs public class Dog extends Animal { public Dog() { } public Dog(String name, int age, String sex) { super(name, age, sex); } @Override public void eat() { System.out.println("Dog eat"); } @Override public void sleep() { System.out.println("Dog sleep"); } @Override public void hobit() { System.out.println("Dog roll"); } } //A test class public class AnimalTest { public static void main(String[] args) { Animal animal1 = new Dog("chinese rhubarb",5,"common"); animal1.introduce(); animal1.eat(); animal1.hobit(); animal1.sleep(); Animal animal2 = new Cat("nono",4,"mother"); animal2.introduce(); animal2.eat(); animal2.hobit(); animal2.sleep(); } }
Operation results
I'm rhubarb. I'm 5 years old. I'm male Dog eat Dog roll Dog sleep I am nono,I'm 4 years old. I'm a mother Cats eat fish Cats play with wool Cat sleep
Interface
The essence is to embody the additional extended abstraction of a real world thing
Interface features:
1) cannot instantiate (cannot create object)
How to instantiate? Instantiate through the sub implementation class (must be a specific class) of the interface - the interface is polymorphic (the most popular when used!)
2) relationship between subclass implementation and interface: implementation relationship
3) subclasses of the interface are either abstract classes or override all abstract methods in the interface
Characteristics of interface members:
Member variable: can only be constant. It is decorated with public static final by default
Constructor: the interface has no constructor
Member method: there are only abstract methods. It is decorated with public abstract by default
Differences between abstract classes and interfaces:
1) Differences in membership
Abstract class:
Member variable: either constant or variable;
Member method: it can be either abstract or non abstract;
Construction method: there are both parametric and nonparametric structures;
Interface:
Member variable: it is a constant, and the default modifier is public static final;
Member methods: can only be abstract methods: default modifier public abstract;
Constructor: there is no constructor in the interface
2) Relationship differences
Relationship between classes: Extensions inheritance relationship
Relationship between class and interface: implementation relationship
Relationship between interfaces: extends inheritance relationship, which supports multiple inheritance
3) Differences between design concepts:
Abstract classes cannot be instantiated. They need to be instantiated through specific subclasses = > is a
The interface cannot be instantiated. It needs to be instantiated through specific subclasses = > like a
eg.
public class EatingOut { public static void main(String[] args) { //Create chef object FoodMenu cooker1 = new ChinaCooker(); FoodMenu cooker2 = new AmricanCooker(); //Create customer object Customer customer = new Customer(cooker1); //Customer orders customer.order(); } } //customer class Customer { /* Cat is a Animal,Any representation that satisfies isa can be set as inheritance. Customer has a FoodMenu,All representations satisfying hasa exist in the form of attributes. */ private FoodMenu foodMenu; public Customer() { } public Customer(FoodMenu foodMenu) { this.foodMenu = foodMenu; } public FoodMenu getFoodMenu() { return foodMenu; } public void setFoodMenu(FoodMenu foodMenu) { this.foodMenu = foodMenu; } public void order(){ foodMenu.shiZiCchaoJiDan(); foodMenu.yuXiangRouSi(); } } //menu interface FoodMenu { void shiZiCchaoJiDan(); void yuXiangRouSi(); } //Chinese Chef class ChinaCooker implements FoodMenu { @Override public void shiZiCchaoJiDan() { System.out.println("Scrambled eggs with tomatoes made by the Chinese chef, great!"); } @Override public void yuXiangRouSi() { System.out.println("The fish flavored shredded pork made by Chinese chef is great!"); } } //Foreign Chef class AmricanCooker implements FoodMenu { @Override public void shiZiCchaoJiDan() { System.out.println("Scrambled eggs with tomatoes made by a western chef, Tilly Sheth"); } @Override public void yuXiangRouSi() { System.out.println("Fish flavored shredded meat made by western chef, Tilly shese"); } }
Operation results
Scrambled eggs with tomatoes made by the Chinese chef, great! The fish flavored shredded pork made by Chinese chef is great!
Relationship between types
is a (inheritance), has a (Association), like a (Implementation)
is a:
Cat is a Animal
Anything that satisfies is a means "inheritance relationship"
A extends B
has a:
I have a pen
Those that can satisfy the has a relationship represent "association relationship"
Association relationship usually exists in the form of "attribute".
like a:
Cook like a foodmenu
Anything that satisfies the like a relationship means "implementation relationship"
Implementation relationships are usually: classes implement interfaces.
Formal parameter and return value problem
If the formal parameter of a method is a method called by a class, how to pass the actual parameter?
Concrete class, call this method, and the actual parameters need to pass the object of the current concrete class
Abstract class, the subclass object of the abstract class that needs to be passed when calling the actual parameters of the method (abstract class polymorphism)
When the interface calls this method, the actual parameters need to be passed are the sub implementation class objects of the current interface (interface polymorphism)
If the return value of a method is a reference type and the final method ends, how to return?
Concrete class: the 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
package
Compile and run
Compilation and operation under the same package:
First mode (manual mode)
1) You need to create the com folder and subfolder qf manually under the current folder
2) Enter the dos console: enter the directory where the current java file is located
javac Source file name(HelloWorld.java)---->HelloWorld.class Bytecode file
3) Put the bytecode file generated in step 2) under the 1)qf subfolder
4) Run: run with package: java package name Class name
java com.qf.HelloWorld
Second mode (automatic mode)
1) Enter the specified directory under dos console directly:
javac -d . java source file(HelloWorld.java)
2) Automatically create the package name and the bytecode file under the package
3) Run: run with package: java package name Class name
java com.qf.HelloWorld
Compilation and running under different packages
1) Net hsbc. Import demo class
2) Net. Net is automatically hsbc. Demo - > compile into
3) Then test Compile java files
4) Run java.com qf. Test
package
First: package appears in the first line of the java source file.
Second: how to compile with package name? javac -d . xxx.java
Third: how to run? java full class name
Add: when you say the class name later, if you bring the package name description, it means the complete class name.
If there is no package description, it represents the simple class name.
import
When is import not needed?
java. No.
Not required under the same package.
Everything else is needed.
eg
import Full class name; import Package name.*; import java.util.Scanner; // Full class name. // Students' question: is this inefficient. // This efficiency is not low, because the compiler will automatically change * into a specific class name when compiling. import java.util.*; // You can't be too lazy to save energy. import java.*; This is not allowed because in java The language stipulates that here*Represents only the names of certain classes
Access control rights
What are the access control permissions?
private | private |
---|---|
public | open |
default | |
protected | under protection |
The above four access control permissions: what is the scope of control?
Private means private and can only be accessed in this class
Public means public and can be accessed from any location
"Default" means that it can only be accessed under this class and the same package
protected means that it can only be accessed in this class, the same package and subclasses
Access modifier | This category | Same package | Subclass | Task location |
---|---|---|---|---|
public | sure | sure | sure | sure |
protected | sure | sure | sure | no way |
default | sure | sure | no way | no way |
private | sure | no way | no way | no way |
Inner class
format
Internal class:
You can define another in one class:
Class B is defined in class A. class B is called the inner class of class A, and class A is the outer class!
Member inner class:
Another class is defined in the member position of one class
Internal classes can access members of external classes, including private classes!
//External class class Outer{ //Member variable public int num = 100 ; private int num2 = 200 ; class Inner{ //Member inner class //A member method of a class within a member public void method(){ System.out.println("method Inner"); System.out.println(); System.out.println(num2); } } //Member methods of external classes public void show(){ //Method of the internal class of the accessed member --- > accessed by creating an internal class object //method() ; Wrong -- Method method method of this class accessed Inner inner = new Inner() ; inner.method(); } } //test public class InnerClassDemo { public static void main(String[] args) { //Create an external class object Outer outer = new Outer() ; outer.show(); } }
External classes access internal classes
1) How do external classes directly access member methods of internal classes?
Format:
External class name Internal class name object name = new external class object () New inner class object ();
class Outer2{ private int num = 20 ; //Member inner class class Inner2{ public void show(){ System.out.println(num); } } //Member methods of external classes public void method(){ // Create an inner class object to access the member methods of the inner class } } //Test class public class InnerClassDemo2 { public static void main(String[] args) { //External class name Internal class name object name = external class object Internal class objects; //Applicable to: directly accessing members of the internal class of a member through an external class (prerequisite: the internal class of the current member is a non static class) Outer2.Inner2 oi = new Outer2().new Inner2() ; oi.show() ; } }
2) About modifiers of inner classes of our members:
On the internal class of the member - add the private decoration: for the security of data, its access - requires the public access and indirect access of the external class
Non static inner classes cannot have static modified variables or methods
Non static internal classes will not be loaded when external classes are loaded, so they cannot have static variables or static methods.
1. static attributes and methods will exist in memory when the class is loaded.
2. To use the static attribute or method of a class, the class must be loaded into the jvm.
Pseudo code give an example: Human body first---There is a heart in the body class Body{ //Internal class: heart private class Heart{ //Join private: ensure data security //operation public void operator(){ System.out.println("Heart bypass Surgery ....") ; } } //External classes provide some public access public void method(){ if("If you're a surgeon"){ Heart heart = new Heart() ; heart.operator() ; } } } //The external class directly accesses the members of the internal class
3) If the internal class of the current member is static, the internal methods, whether static or non static, can only access the static members of the external class, including private members!
How to directly access the members of the static member inner class?
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 } }