Process oriented & object oriented
Process oriented
The steps are simple and clear. What to do in the first step and what to do in the second part...
Facing the process is suitable for dealing with some simple problems
Linear problem
object-oriented
- Birds of a feather flock together, the thinking mode of classification. When thinking about problems, we will first solve what classifications are needed, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification.
- Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation.
For describing complex things, we need to grasp them from the macro and analyze them reasonably as a whole. We need to use object-oriented thinking to analyze the overall system. However, specific to micro operation, it still needs process oriented thinking to deal with it.
What is object oriented
-
Object oriented programming: oop
-
Essence: organize code in the form of class and organize (encapsulate) data in the form of object.
-
abstract
-
Three characteristics:
- encapsulation
- Inheritance: subclass, parent class
- polymorphic
-
From the perspective of epistemology, there are objects before classes. Objects are concrete things. Class is abstract, which is the abstraction of objects
-
From the perspective of code operation, there are classes before objects. A class is a template for an object.
Review methods and deepening
Method of definition
Modifier return type
/* Modifier return value type method name (...) { //Method body return Return value; } */ public String sayHello(){ return "hello,world"; } public void hello(){ return ; } public int max (int a,int b){ return a>b?a:b;//Ternary operator }
break: jump out of switch and end the difference between loop and return
Return: end the method and return a result!
Method name: pay attention to the specification and see the name and meaning
Parameter list: (parameter type, parameter name)...
Exception thrown: questions, explained later
// Array subscript out of bounds exception: Arrayindexoutofbounds public void readFile(String file) throws IOException{ }
Method call: recursion
There are two kinds of method calls. Generally, non static methods are used more.
Static method:
package com.oop.demo01; //Student class public class Student { //Static method public static void say(){ System.out.println("The student spoke"); } }
package com.oop.demo01; public class Demo02 { //static method public static void main(String[] args) { Student.say(); }
Non static method:
package com.oop.demo01; //Student class public class Student { //Non static method public void say(){ System.out.println("The student spoke"); } }
package com.oop.demo01; public class Demo02 { //Non static method public static void main(String[] args) { //Instantiate this class new //Object type object name = object value Student student=new Student(); student.say(); } }
extend
public void a(){ b(); } public void b(){ }
public static void a(){ b(); } public static void b(){ }
Error call:
//Loaded with class public static void a(){ b(); } //Class does not exist until it is instantiated public void b(){ }
Formal and argument
package com.oop.demo01; //Non static method public class Demo03 { public static void main(String[] args) { int add= new Demo03().add(1,2); System.out.println(add); } public int add(int a,int b){ return a+b; } }
package com.oop.demo01; //Static method public class Demo03 { public static void main(String[] args) { //The types of actual parameters and formal parameters should correspond! int add= Demo03.add(1,2); System.out.println(add); } public static int add(int a,int b){ return a+b; } }
Value passing and reference passing
Value transfer: copy one
Reference passing: create a new shortcut
package com.oop.demo01; //pass by value public class Demo04 { public static void main(String[] args) { int a=1; System.out.println(a); Demo04.change(a);//1 } //The return value is null public static void change(int a){ a=10; } }
Output result: 1
package com.oop.demo01; //Reference passing: object, essence or value passing public class Demo05 { public static void main(String[] args) { Perosn perosn=new Perosn(); System.out.println(perosn.name);//null Demo05.change(perosn); System.out.println(perosn.name);//ha-ha } public static void change(Perosn perosn){ //Perosn is an object: point to -- > perosn perosn = new perosn(); This is a specific person who can change attributes! perosn.name="ha-ha"; } } //There can only be one public class in a class, but there can be multiple class classes //Defines a Perosn class with an attribute: name class Perosn{ String name;//null }
this keyword
Creation of classes and objects
Relationship between class and object
- Class is an abstract data type. It is the overall description / definition of a certain kind of things, but it can not represent a specific thing
- Objects are concrete instances of abstract concepts.
- Zhang San is a concrete example of man, and Wang CAI in Zhang San's family is a concrete example of dog.
- It is a concrete instance rather than an abstract concept that can reflect the characteristics and functions.
Creating and initializing objects
- Create an object using the new keyword
- When using the new keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be called
- Class constructors, also known as construction methods, must be called when creating objects. And the constructor has the following two characteristics:
- 1. Must be the same as the name of the class
- 2. There must be no return type and void cannot be written
package com.oop.demo02; //Student class public class Student { //Properties: Fields String name;//null int age;//null //method public void study(){ System.out.println(this.name+"I'm learning"); } }
package com.oop.demo02; //A project should have only one main method public class Application { public static void main(String[] args) { //Class: abstract, instantiated //Class instantiation will return an object of its own! //Student object is a concrete instance of student class! Student student = new Student(); Student xiaoming = new Student(); Student xiaohong = new Student(); xiaoming.name="Xiao Ming"; xiaoming.age=3; System.out.println(xiaoming.age); System.out.println(xiaoming.name); xiaohong.name="Xiao Hong"; xiaohong.age=4; System.out.println(xiaohong.name); System.out.println(xiaohong.age); } }
Constructor explanation
Show class file
-
Click the project structure button on the toolbar
-
Add Content Root on the right
-
Find out file - apply - add
-
Return to the idea page to display the class file
constructor
Class constructors, also known as construction methods, must be called when creating objects. And the constructor has the following two characteristics:
-
1. Must be the same as the name of the class
-
2. There must be no return type and void cannot be written
package com.oop.demo02; //Java--->class public class Person { //Even if a class doesn't write anything, it will have a method (parameterless construction) //Display definition constructor String name; //Instantiation initial value //1. When using the new keyword, there must be a constructor //The essence is to call the constructor //2. Used to initialize values public Person(){ this.name="hahaha"; } //Parametric Construction: once a parametric construction is defined, a nonparametric construction must display the definition public Person(String name){ this.name=name; } } //alt + insert automatic constructor //The above method defaults to parametric construction //Select Select None to construct a parameterless structure /* public static void main(String[] args) { //new Instantiated an object Person person = new Person("qzzz"); System.out.println(person.name);//hahaha } */
Create object memory analysis
There are objects in the heap; Including part of the method area
The stack is full of methods and method references
package com.oop.demo03; public class Pet { public String name; public int age; //Nonparametric structure public void shout(){ System.out.println("Let out a cry"); } } /* public static void main(String[] args) { Pet dog = new Pet(); dog.name="Wangcai "; dog.age=3; dog.shout(); System.out.println(dog.name); System.out.println(dog.age); Pet cat = new Pet(); } */
- Create object shortcut key new + class name (), and then press Alt+Enter to generate it automatically
Simple summary classes and objects
package com.oop; import com.oop.demo02.Person; import com.oop.demo03.Pet; public class Application { public static void main(String[] args) { /* 1.Classes and objects A class is a template: abstract, and an object is a concrete instance 2.method Define and call! 3.Corresponding reference Reference type: basic type (8) Objects are operated by reference: stack -- > heap 4.Attribute: Field member variable Default initialization: Number: 0.0 char: u0000 boolean: false Reference: null Modifier attribute type attribute name = attribute value! 5.Object creation and use -You must use the new keyword to create an object, and the constructor Person kk=new Person(); -Object properties: KK name -Object method: KK sleep() 6.Class: Static properties Dynamic behavior method 'Encapsulation, inheritance, polymorphism ' */ } }
Packaging details
package com.oop.demo04; //Class private: private public class Student { //Property private private String name;//name private int id; //Student number private char sex; //Gender private int age; //Age //Provide some operational methods! //Provide some public get and set methods //get this data public String getName(){ return this.name; } //set sets a value for this data public void setName(String name){ this.name=name; } // alt + insert automatically generates get and set methods //Or find Generate in the navigation bar Code //Getter and Setter column public int getId() { return id; } public void setId(int id) { this.id = id; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { if(age>120||age<0){//wrongful this.age = 3; }else { this.age=age; } } }
package com.oop; import com.oop.demo04.Student; /* 1.Improve program security and protect data 2.Implementation details of hidden code 3.Unified interface 4.System maintainability has increased */ public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("day"); //Determine whether the two methods are the same: //1. Method name; 2. Parameter list System.out.println(s1.getName()); s1.setAge(999);//illegal System.out.println(s1.getAge()); } }
-
The dew that should be exposed, the hide that should be hidden
- Our programming should pursue "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by themselves, and external interference is not allowed; Low coupling: only a small amount of methods are exposed for external use.
-
Encapsulation (data hiding)
- Usually. Direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding.
-
Remember this sentence: property private, get/set
-
It is mostly used for attributes and less for methods
External cannot be accessed directly. An interface can be called through internal method access
get/set method
//Provide some operational methods! //Provide some public get and set methods //get this data public String getName(){ return this.name; } //set sets a value for this data public void setName(String name){ this.name=name; }
Student s1 = new Student(); s1.setName("day"); System.out.println(s1.getName());
Packaging reliability
public int getAge() { return age; } public void setAge(int age) { if(age>120||age<0){//wrongful this.age = 3; }else { this.age=age; }
s1.setAge(999);//illegal System.out.println(s1.getAge());
- Improve program security and protect data
- Implementation details of hidden code
- Unified interface
- System maintainability has increased
Whether the judgment method is the same
1. Method name;
2. Parameter list;
Automatic generator
alt + insert automatically generates get and set methods
Or find Generate in the navigation bar Code
Getter and Setter column
inherit
-
The essence is to abstract a group of classes, so as to realize better modeling of the real world.
-
Extensions means "extension". A subclass is an extension of a parent class.
-
JAVA classes only have single inheritance, not multiple inheritance! A son has only one father, and a father can have multiple sons.
-
Inheritance is the relationship between classes. In addition, the relationships between classes include dependency, composition, aggregation and so on.
-
Two classes of inheritance relationship, one is a child class (derived class) and the other is a parent class (base class). The subclass inherits from the parent class and is represented by the keyword extends.
-
In a sense, there should be a "is a" relationship between subclasses and superclasses
-
object class
-
super
-
Method rewrite
Relationship between subclass and parent
- The subclass inherits from the parent class and is represented by the keyword extends.
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG cukmxrjk-1645280551616) (C: \ users \ PC \ desktop \ object-oriented \ 7.png)]
package com.oop.demo05; //Person: parent class public class Person { }
package com.oop.demo05; // Student is person: derived class, subclass public class Student extends Person{ }
package com.oop.demo05; //Teacher is: derived class, subclass public class Teacher extends Person { }
- A subclass can inherit all the methods of the parent class.
Four modifiers
//Public public
//Private private
//Default default (you don't need to write)
//protect protected
package com.oop.demo05; //Person: parent class public class Person { //Four modifiers //Public public //Private private //Default default //protect protected private int money =10_0000_0000; public void say(){ System.out.println("Said a word!"); } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
package com.oop.demo05; // Student is person: derived class, subclass //If a subclass inherits the parent class, it will have all the methods of the parent class public class Student extends Person{ }
package com.oop; import com.oop.demo05.Student; public class Application { public static void main(String[] args) { Student student = new Student(); student.say(); System.out.println(student.getMoney()); } }
Shortcut key object class
Ctrl+H
In java, all classes inherit the object class directly or indirectly by default.
In person Pressing Ctrl+H in Java will bring up the inheritance framework
At student.com Pressing Ctrl+H in Java will bring up the inheritance framework
super detailed explanation
-
private things cannot be inherited
-
super is an attribute that can obtain the previous class
package com.oop.demo05; //Person: parent class //In java, all classes inherit the object class directly or indirectly by default public class Person { protected String name="kk"; public void print(){ System.out.println("Person"); } }
package com.oop.demo05; // Student is person: derived class, subclass //If a subclass inherits the parent class, it will have all the methods of the parent class public class Student extends Person{ private String name="hh"; public void print(){ System.out.println("Student"); } public void text1(){ print(); this.print(); super.print(); } public void text(String name){ System.out.println(name); System.out.println(this.name); System.out.println(super.name); } }
package com.oop; import com.oop.demo05.Person; import com.oop.demo05.Student; import javax.naming.Name; public class Application { public static void main(String[] args) { Student student = new Student(); student.text("jj"); student.text1(); } }
Constructor limitations
Hidden code: the parameterless construction of the parent class is called by default
The constructor that calls the parent class must be on the first line of the child class
public class Person { public Person() { System.out.println("Person No participation"); } }
public class Student extends Person{ public Student() { //Hidden code: the parameterless construction of the parent class is called by default //The constructor that calls the parent class must be on the first line of the child class //super();//this () is consistent, but also on the same line. Therefore, only one parent class or this class can be called System.out.println("Student No participation"); } }
public class Application { public static void main(String[] args) { Student student = new Student(); } }
Attention
- super calls the constructor of the parent class, which must be in the first place of the constructor
- super must only appear in subclass methods or constructor methods
- super and this cannot call construction methods at the same time
vs this
The objects represented are different:
this: the object of the caller itself
super: represents the application of the parent object
premise
this: it can be used without inheritance
super: can only be used under the condition of inheritance
Construction method
this(); Construction of this class
super(); Construction of parent class
Method rewrite
Rewriting is the rewriting of methods; It has nothing to do with attributes
be careful
Static methods can only be inherited and cannot be overridden
It is rewritten when the indication in the figure below appears (circle c)
package com.oop.demo05; //inherit public class A extends B { //Override override @Override//Comments: functional comments! public void test() { System.out.println("A=>test()"); } }
package com.oop.demo05; //Rewriting is the rewriting of methods; It has nothing to do with attributes public class B { public void test(){ System.out.println("B=>test()"); } }
package com.oop; import com.oop.demo05.A; import com.oop.demo05.B; public class Application { public static void main(String[] args) { //Static methods and non static methods are very different! // Static method: //Method is only related to the data type defined on the left //Non static: override A a = new A(); a.test();//A //A reference to a parent class points to a child class B b = new A();//The subclass overrides the method of the parent class b.test();//B } }
summary
For example, rabbits are a subclass of animals. When it comes to rabbits, the method of eating naturally needs to be rewritten
Rewriting: inheritance relationship is required. The subclass rewrites the method of the parent class!
- Method names must be the same
- The parameter list must be the same
- Modifier: the scope can be expanded but not reduced: public > protected > Default > private
- Exception thrown: the scope can be reduced, but not expanded; Classnotfoundexception -- > exception (large)
When overridden, the methods of subclasses and superclasses must be consistent; Different methods!
Why rewrite?
-
The function of the parent class and the subclass are not necessarily required or satisfied!
Shortcut Ctrl+O
polymorphic
-
Dynamic compilation: Type: extensibility
-
The same method can adopt many different behavior modes according to different sending objects
-
The actual type of an object is determined, but there are many types of references that can point to the object
-
Conditions for the existence of polymorphism
- There is an inheritance relationship
- Subclass overrides parent method
- A parent class reference points to a child class object
-
Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
package com.oop.demo06; public class Person { public void run(){ System.out.println("run"); } }
package com.oop.demo06; public class Student extends Person { @Override //rewrite public void run() { System.out.println("son"); } public void eat(){ System.out.println("ear"); } }
package com.oop; import com.oop.demo06.Person; import com.oop.demo06.Student; public class Application { public static void main(String[] args) { //The actual type of an object is determined //new Student(); // new Person(); //The type of reference that can be pointed to is uncertain //The reference of the parent class points to the child class //The methods that students can call are their own or inherit the parent class! Student s1 = new Student(); //The Person parent type can point to subclasses, but cannot call methods unique to subclasses Person s2 = new Student(); Object s3 = new Student(); s2.run();//The subclass overrides the method of the parent class and executes the method of the subclass s1.run(); //The methods that can be executed by the object mainly depend on the type on the left of the object, which has little to do with the right! //s2.eat(); Cannot call } }
The output results are as follows:
son
son
Process finished with exit code 0
Polymorphic considerations
-
Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
-
The parent and child classes are related, otherwise the type conversion exception is ClassCastException!
-
Existence conditions: inheritance relationship, method override. The subclass overrides the method of the parent class and executes the method of the subclass
Some methods cannot be overridden:
- static method, which belongs to class, does not belong to instance
- final constant:
- Private method private
-
The reference of the parent class points to the object of the child class; Father f1=new Son();
instanceof type conversion (reference type)
instanceof function
Determine what type an object is and whether the two classes are parent-child
It is used to judge whether the two types are similar and pave the way for the following forced type conversion
package com.oop; import com.oop.demo06.Person; import com.oop.demo06.Student; import com.oop.demo06.Teacher; public class Application { public static void main(String[] args) { //Object>Person>Student //Object>Person>Teacher //Object>String Object object = new Student(); //Note the o case in the object //System.out.println(X instanceof Y); Can it be compiled! System.out.println(object instanceof Student);//true System.out.println(object instanceof Person);//true System.out.println(object instanceof Object);//true System.out.println(object instanceof Teacher);//False System.out.println(object instanceof String);//False System.out.println("======================"); Person person=new Student(); System.out.println(person instanceof Student);//true System.out.println(person instanceof Person);//true System.out.println(person instanceof Object);//true System.out.println(person instanceof Teacher);//False //System.out.println(person instanceof String);// Compilation error System.out.println("======================"); Student student = new Student(); System.out.println(student instanceof Student);//true System.out.println(student instanceof Person);//true System.out.println(student instanceof Object);//true //System.out.println(student instanceof Teacher);// Compilation error //System.out.println(student instanceof String);// Compilation error } }
public class Teacher extends Person { }
public class Student extends Person { }
public class Person { }
Type conversion
package com.oop; import com.oop.demo06.Person; import com.oop.demo06.Student; import com.oop.demo06.Teacher; public class Application { public static void main(String[] args) { //Conversion between types: basic type conversion 64 32 16 8 //Forced conversion from parent-child high to low //High and low //Force conversion Person obj=new Student(); //obj.go(); Error! There is no go method in the Person class //obj converts this object to Student type, and you can use Student type methods! Student student = (Student) obj; student.go(); //Or ((student) obj) go(); //Low to high direct conversion //However, some methods will be lost when a subclass is converted to a parent class Student qaz = new Student(); qaz.go(); Person person=qaz; //person.go() error! } }
summary
- The reference of the parent class points to the object of the child class
- The child class is converted to the parent class, and the upward transformation is directly converted; Loss method
- The parent class is transformed into a child class and transformed downward; Forced conversion; Lost accuracy
- Convenient method call and reduce duplicate code!
static
Properties and methods
package com.oop.demo07; //static: public class Student { private static int age;//Static variable multithreading! private double score;//Non static variable public void run(){ } public static void go(){ } public static void main(String[] args) { //static pair method: new Student().run();//Non static Student.go();//static state go();//static state //static pair class: Student s1 = new Student(); //Static variables are shared by all objects (instances) of a class. When the class is called directly, it indicates that this variable is static System.out.println(Student.age); System.out.println(s1.age); System.out.println(s1.score); } }
Code block
package com.oop.demo07; public class Person { /* { //Code block (anonymous code block) Function: assign initial value } static { //Static code block The earliest execution is loaded together with the class Execute only once } */ //Static > anonymous > construct { System.out.println("Anonymous code block"); } static { System.out.println("Static code block"); } public Person(){ System.out.println("Construction method"); } public static void main(String[] args) { Person person1 = new Person(); System.out.println("==================="); Person person2 = new Person(); } }
The output results are as follows:
Static code block Anonymous code block Construction method =================== Anonymous code block Construction method |
---|
Static import package
package com.oop.demo07; //Static import package import static java.lang.Math.PI; import static java.lang.Math.random; public class Test { public static void main(String[] args) { // Before importing the package // System.out.println(Math.random()); System.out.println(random());//After importing the package System.out.println(PI); } }
If a constant is modified, it cannot be inherited
abstract class
- The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method; If you modify a class, it is an abstract class.
- There can be no abstract method in abstraction, but the class with abstract method must be declared as abstract class.
- Abstract classes can create objects without using the new keyword. It allows subclasses to inherit.
- Abstract methods have only method declarations and no method implementations. They are used to implement subclasses.
- If a subclass inherits an abstract class, it must implement an abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class.
package com.oop.demo08; //Abstract abstract class: class extensions: single inheritance (interfaces can inherit more than one) public abstract class Action { //Constraint ~ someone helped me achieve it~ //Abstract, abstract method, only method name, no method implementation! public abstract void doSomthing(); }
package com.oop.demo08; //If the subclass inherits the abstract class, it must implement the abstract method (override) that the abstract class does not implement, // Otherwise, the subclass should also be declared as an abstract class. public class A extends Action { @Override public void doSomthing() { } }
characteristic
- Do not use new, you can only rely on subclasses to implement it; Constraints!
- Ordinary methods can be written in abstract classes;
- Abstract methods must be in abstract classes;
- Abstract: constraints!
- Constructor exists for abstract class
- Significance: prevent duplicate codes; Improve development efficiency
Definition and implementation of interface
-
Common class: only concrete implementation
-
Abstract classes: concrete implementations and specifications (abstract methods) are available!
-
Interface: only specification! I can't write professional constraints! Separation of constraints and Implementation: interface oriented programming
-
An interface is a specification, and a definition is a set of rules embodied in the real world, "if you are..., you must be able to..." My thoughts. If you are a car, you must be able to run. The essence of interface is contract.
-
The keyword for declaring a class is class, and the keyword for declaring an interface is interface
Definition of interface
package com.oop.demo09; public interface TimeService { void timer(); }
package com.oop.demo09; //Abstract thinking ~ Java Architect //Keywords defined by interface public interface UserService { //All definitions in the interface are actually Abstract public abstract s //Interfaces generally have an implementation class //Constants ~ constants in the interface are public static constants int AGE=99; void add(String name); void delete(String name); void update(String name); void query(String name); }
Implementation of interface
package com.oop.demo09; //Class can implement the interface through the keyword implements interface //If you implement the class of the interface, you need to rewrite the methods in the interface //Multi inheritance ~ realize multi inheritance by using interface~ public class UserServiceImpl implements UserService ,TimeService{ @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { } }
Function of interface
- constraint
- Define some methods for different people to implement~
- The methods in the interface are abstract classes public abstract
- Constants in the interface are public static final
- The interface cannot be instantiated (the method has no body), and the interface has no construction method
- implements can implement multiple interfaces
- If you implement the class of the interface, you need to rewrite the methods in the interface
Inner class
- Internal class is to define another class inside a class, such as. If a class B is defined in class A, class B is called an internal class relative to class A, and class A is an external class relative to class B.
Member inner class
package com.oop.demo10; public class Outer { private int id=10; public void out(){ System.out.println("This is the method of an external class"); } public class Inner{ public void in(){ System.out.println("This is the method of the inner class"); } //Get the private properties of the external class~ public void getID(){ System.out.println(id); } } }
package com.oop; import com.oop.demo10.Outer; public class Application { public static void main(String[] args) { //new Outer outer = new Outer(); //Instantiate the inner class through the outer class~ Outer.Inner inner = outer.new Inner(); inner.in(); inner.getID(); } }
The output results are as follows:
This is the method of the inner class 10 |
---|
- A java class can have multiple class classes, but only one public class
Local inner class
public class Outer { //Local inner class public void method(){ class Inner{ public void in(){ } } } }
Anonymous Inner Class
package com.oop.demo10; public class Test { public static void main(String[] args) { //An initialization class without a name is saved in a variable without adding an instance~ new Apple().eat(); // Apple apple = new Apple(); UserService userService=new UserService(){ @Override public void hello() { } }; } } class Apple{ public void eat(){ System.out.println("1"); } } interface UserService{ void hello(); }
Static inner class
;
public void out(){
System.out.println("this is the method of the external class");
}
public class Inner{
public void in(){
System.out.println("this is the method of the inner class");
}
//Get the private properties of the external class~ public void getID(){ System.out.println(id); } }
}
```java package com.oop; import com.oop.demo10.Outer; public class Application { public static void main(String[] args) { //new Outer outer = new Outer(); //Instantiate the inner class through the outer class~ Outer.Inner inner = outer.new Inner(); inner.in(); inner.getID(); } }
The output results are as follows:
This is the method of the inner class 10 |
---|
- A java class can have multiple class classes, but only one public class
Local inner class
public class Outer { //Local inner class public void method(){ class Inner{ public void in(){ } } } }
Anonymous Inner Class
package com.oop.demo10; public class Test { public static void main(String[] args) { //An initialization class without a name is saved in a variable without adding an instance~ new Apple().eat(); // Apple apple = new Apple(); UserService userService=new UserService(){ @Override public void hello() { } }; } } class Apple{ public void eat(){ System.out.println("1"); } } interface UserService{ void hello(); }