object-oriented
oop: organize code in the form of classes and organize (encapsulate) data in the form of objects
- abstract
- Three characteristics: encapsulation inheritance polymorphism;
Value passing and reference passing
//pass by value public class Demo03 { public static void main(String[] args) { int a = 1; System.out.println(a);//1 Demo03.change(a); System.out.println(a);//1 } public static void change(int a){ a = 10; } }
//Reference passing: object, essence or value passing public class Demo02 { public static void main(String[] args) { Person person = new Person(); System.out.println(person.name);//null Demo02.change(person); System.out.println(person.name);//hqw } public static void change(Person person){ person.name = "hqw"; } } //The person class is defined and has an attribute: name class Person{ String name; }
Relationship between class and object
- Classes and objects
- Class is an abstract data type. It is an overall description of a certain kind of things, but it can not represent a specific thing
- Objects are concrete instances of abstract concepts
-
method
Define and call
-
Corresponding reference
Reference type: basic type
Objects are operated by reference: stack - > heap
-
Attribute: Field member variable
Default initialization:
Number: 0, 0.0
char: u0000
Reference: null
Modifier attribute type attribute name = attribute value
-
Object creation and use
- You must use the new keyword to create an object. The constructor Person hqw = new Person();
- Object's properties HQW name
- Object method: HQW sleep();
-
Class:
Static properties
Dynamic behavior method
Create initialization object
-
Create an object using the new keyword
-
When using new, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be called
-
The constructor in the class also becomes a construction method, which must be called when creating an object. And the constructor has the following two characteristics:
- Must be the same as the name of the class
- There must be no return type and void cannot be written
package Demo02; public class Person { //If a constructor doesn't write anything, there will be a method //Explicit definition constructor String name; //Instantiation initial value //1. using the new keyword is essentially calling the constructor //2. Used to initialize values public Person(){ this.name = "qinjinga"; } //Parameterized Construction: once a parameterized construction is defined, no parameters must be explicitly defined public Person(String name){ this.name = name; } //alt+insert automatically creates constructors } /* public class Application{ public static void main(String[] args) { //new Instantiated an object Person person = new Person("hqw"); System.out.println(person.name); } } */
Constructor function:
- The essence of new is to call the constructor
- Initializes the value of the object
Note:
- After defining a parameterless construction, if a parameterless construction is used, a parameterless construction is defined
Memory analysis
package Demo03; public class Pet { String name; int age; public void shout(){ System.out.println("Let out a cry"); } }
package Demo03; public class Application { 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); } }
encapsulation
High cohesion, low coupling
//Class: private public class Student { private String name;//name private int id; private char sex; private int age; //Provide some methods that can manipulate this property //Provide public get and set methods public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public void setAge(int age){ if (age>120 || age<0){ this.age=3; }else { this.age = age; } } //alt + insert automatically generates get and set methods }
- Improve program security and protect data
- Implementation details of hidden code
- Unified interface
- Improve maintainability
inherit
Inheritance is the abstraction of a group of classes, so as to realize better modeling of the real world
Extensions is an extension of a subclass to a parent class
There is only single inheritance in Java (a son can only have one father, but a father may have multiple sons)
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 parent classes.
package Demo05; //Parent class public class Person { //public //protected //default //private cannot inherit 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 Demo05; //Subclass: if you inherit the parent class, you have all the methods of the parent class public class Student extends Person{ //Ctrl + H brings up the inheritance tree }
import Demo05.Student; public class Application { public static void main(String[] args) { Student student = new Student(); student.say(); System.out.println(student.getMoney()); } }
In java, all classes inherit the object class directly or indirectly by default
public class Person { protected String name = "kuangshen"; }
public class Student extends Person{ private String name = "qinjiang"; public void test1(String name){ System.out.println(name);//Qin Jiang System.out.println(this.name);//qinjiang System.out.println(super.name);//kuangshen } }
public class Application { public static void main(String[] args) { Student student = new Student(); student.test1("Qin Jiang"); } }
//Parent class public class Person { public void print(){ System.out.println("Person"); } }
//Subclass: if you inherit the parent class, you have all the methods of the parent class public class Student extends Person{ public void print(){ System.out.println("Student"); } public void test2(){ print();//Student this.print();//Student super.print();//Person } }
public class Application { public static void main(String[] args) { Student student = new Student(); student.test2(); } }
//Parent class public class Person { public Person(){ System.out.println("Person Nonparametric structure"); } }
//Subclass: if you inherit the parent class, you have all the methods of the parent class public class Student extends Person{ //The parameterless construction call of the parent class is hidden: super(); //Calling the constructor of the parent class must be in the first line of the subclass constructor public Student(){ System.out.println("Student Nonparametric structure"); } }
public class Application { public static void main(String[] args) { Student student = new Student(); //Output: //Person parameterless construction //Student parameterless construction } }
super note:
- 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 reference of the parent class object
- premise
- this: it can be used without inheritance
- super: can only be used under inheritance conditions
- Construction method:
- This: the structure of this class
- super: Construction of parent class
Method rewrite
Rewriting is the rewriting of methods and has nothing to do with properties
public class A extends B{ public static void test(){ System.out.println("A=>test()"); } }
public class B { public static void test() { System.out.println("B=>test()"); } }
public class Application { public static void main(String[] args) { //Method is only related to the data type defined on the left A a = new A(); a.test(); //A reference to a parent class points to a child class B b = new A(); b.test(); } }
↑ the call result of static method is:
A=>test()
B=>test()
Rewriting is only related to non static methods!
public class A extends B{ public void test(){ System.out.println("A=>test()"); } }
public class B { public void test() { System.out.println("B=>test()"); } }
public class Application { public static void main(String[] args) { A a = new A(); a.test(); //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(); } }
Output:
A=>test()
A=>test()
Rewritten keywords can only be public, not private
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 range can be expanded but not reduced
- Exception thrown: the scope can be narrowed but not expanded: classnotfoundexception -- > exception
When overridden, the methods of subclasses and superclasses must be consistent; Different methods
Why rewrite:
- The functional subclasses of the parent class are not necessarily required or satisfied
- Alt+Insert : override
polymorphic
public class Person { public void run(){ System.out.println("run"); } }
public class Student extends Person { @Override public void run(){ System.out.println("son"); } public void eat(){ System.out.println("ear"); } }
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 methods that students can call are their own or inherit the parent class Student s1 = new Student(); //The parent type of Person can point to subclasses, but cannot call methods unique to subclasses Person s2 = new Student();//The reference of the parent class points to the type of the child class Object s3 = new Student(); s2.run();//The subclass overrides the method of the parent class and executes the method of the subclass s1.run(); s1.eat(); s2.eat();//Error reporting, which methods the object can point to, mainly depends on the type on the left, which has little to do with the right } }
matters needing attention:
- Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
- There is a connection between parent class and child class. Type conversion exception! ClassCastException!
- Existence conditions: inheritance relationship, method needs to be rewritten, reference of parent class points to subclass object, Father f1 = new Son()
- Methods that cannot be overridden:
- static method: belongs to class but not instance
- final constant
- private method
instanceof and cast
Instanceof (type conversion) refers to the type and determines what type an object is
public class Application { public static void main(String[] args) { //Object > String //Object > Person > Teacher //Object > Person > Student Object object = new Student(); 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 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 } }
Force conversion
public class Person { public void run(){ System.out.println("run"); } }
public class Student extends Person { public void go(){ System.out.println("go"); } }
public class Application { public static void main(String[] args) { //Conversion between types: parent (high) and child (low) //Forced type conversion is not required for low to high conversion, and high to low conversion is required //High and low Person obj = new Student(); //By converting this object to student type, you can use the method of student type Student student = (Student) obj; student.go(); //Abbreviated as ((student) obj) go //When a subclass is converted to a parent class, it may lose its own method Student student1 = new Student(); student.go(); Person person = student1;//Low to high automatic rotation person.go()//report errors } }
- The reference of the parent class points to the object of the child class (irreversible)
- Convert a subclass to a parent class and transform upward: methods may be lost
- Convert a parent class to a child class and transform downward: Cast
- Facilitate method calls and reduce duplicate code
static keyword
public class Student { private static int age;//Static variable multithreading! private double score;//Non static variable public void run(){ //Non static methods can directly call things in static methods go(); } public static void go(){ //Non static methods cannot be called directly } public static void main(String[] args) { Student s1 = new Student(); System.out.println(age);//age.sout System.out.println(s1.age); System.out.println(score);//report errors System.out.println(s1.score); go();//Call static method new Student().run();//Non static call with object } }
public class Person { //2: Assign initial value { System.out.println("Anonymous code block"); } //1: Execute only once static { System.out.println("Static code block"); } //3 public Person(){ System.out.println("Construction method"); } public static void main(String[] args) { Person person = new Person(); Person person2 = new Person();//The second execution has no static code block } }
Execution sequence ↑
//Static import package import static java.lang.Math.random; public class Test { public static void main(String[] args) { System.out.println(random());//If you write the import package, you don't need to write math random() } }
final class 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 the abstract class of the class
-
You can't new abstract class, you can only rely on subclasses to implement it; Constraints!
-
Abstract methods must be in abstract classes
-
Abstract classes can have ordinary methods
-
Abstract methods have only method declarations and no method implementations. They are implemented in subclasses
-
If a subclass inherits an abstract class, it must implement the abstract method that the abstract class does not implement, otherwise the subclass is also set as an abstract class
package Demo09; //Abstract class extensions: single inheritance interface can inherit more than one public abstract class Action { //Constraint someone to help us achieve //Only abstract constraints are not implemented public abstract void doSomething(); }
package Demo09; //All methods of an abstract class that inherit its subclasses must implement its methods unless they are also abstract classes public class A extends Action{ @Override public void doSomething() { } }
Interface
interface
Common class: only concrete implementation
Abstract classes: concrete implementations and specifications (abstract methods) are available!
Interface: only specification! I can't write my own method
The essence of interface is contract
package Demo10; //Abstract thinking is the key //The keywords defined by interface and interfaces need to have implementation classes public interface UserService { //Constant public static final int AGE = 99; //All definitions in the interface are abstract public abstract void run(String name); void delete(String name); void update(String name); void query(String name); }
public interface TimeService { void timer(); }
//Class can implement the interface implements //If you implement the class of the interface, you need to rewrite the methods in the interface //Implementing multi inheritance with interface public class UserServiceImpl implements UserService, TimeService{ @Override public void run(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { } }
effect:
- constraint
- Define some methods for different people to implement
- Methods: public abstract
- Constants are: public static final
- The interface cannot be instantiated. There is no constructor in the interface
- implements can implement multiple interfaces
- You must override the methods in the interface
Inner class
Define another class inside a class
There can be multiple class classes in a java class, but there can only be one public class
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"); } //Gets the private property of the external class public void getID(){ System.out.println(id); } } }
public class Application{ public static void main(String[] args) { Outer outer = new Outer(); //Instantiate the inner class through the outer class Outer.Inner inner = outer.new Inner(); inner.in(); inner.getID(); } }
package Demo11; public class Test { public static void main(String[] args) { //Anonymous inner class: there is no name to initialize the class, so there is no need to save the instance to the variable new Apple().eat(); UserService userService = new UserService() { @Override public void hello(){ } }; } } class Apple{ public void eat(){ System.out.println("eat"); } } interface UserService{ void hello(); }