object-oriented
- The essence of object-oriented programming is to organize code in the form of classes and encapsulate data in the form of objects
1. Relationship between class and object
- Class is an abstract data type. It is the overall description / definition of a certain kind of transaction, but it can not represent a specific thing
- Person class, Pet class, Car class, etc. these classes are used to describe / define the characteristics and behavior of a specific thing
- Objects are concrete instances of abstract concepts
- Zhang San is a specific example of a person, and Laifu in Zhang San's family is a specific example of a dog.
- It is a concrete instance rather than an abstract concept that can reflect the characteristics and functions.
2. Create and initialize 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 creation:
package com.oop.demo02; //Student class public class Student { //Properties: Fields String name;//null int age;//0 //method public void study(){ System.out.println(this.name+"Students are studying"); } }
Object creation:
package com.oop.demo02; //There should be only one main method in a project public class Application { public static void main(String[] args) { //Class: abstract and needs to be instantiated //Class will return its own object after instantiation //A student object is a concrete instance of a student class Student student = new Student(); Student xiaohong = new Student(); Student abin = new Student(); abin.name="Abin"; abin.age=16; System.out.println(abin.name); System.out.println(abin.age); } }
- Constructors in classes, also known as construction methods, must be called when creating objects. 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
Example: class and constructor
package com.oop.demo02; //Java ------ > class Ctrl + Alt + Shift + s open the project structure to add the class file under the out folder public class Person { //A class will have a method (constructor) even if it doesn't write anything //Display definition constructor String name; int age; //Instantiation initial value //1. Using the new keyword is essentially calling the constructor //2. Used to initialize values public Person() {//Parameterless constructor //this.name = "kazk"; } //Parameterized Construction: once a parameterized construction is defined, the definition must be displayed if there is no parameter, otherwise it will be invalid //Will match according to the given parameters (method overloading) public Person(String name, int age) { this.name = name; this.age = age; } //alt+insert will quickly generate constructors } /* public static void main(String[] args) { //new Instantiated an object Person person = new Person("Kazik ", 4); System.out.println(person.name);//Kha'Zix } Constructor: 1.Must be the same as the name of the class 2.There must be no return type and void cannot be written effect: 1.new The essence is to call the constructor 2.Initializes the value of the object Note: 1.After defining a parameterized construct, if you want to use a parameterless construct, you can define a parameterless construct //Alt+Insert */
Example: object
package com.oop.demo02; //There should be only one main method in a project public class Application { public static void main(String[] args) { //new instantiates an object Person person = new Person("Kha'Zix "); System.out.println(person.name);//Kha'Zix } }
Output diagram
Summary class and object
- Classes and objects
- A class is a template: an abstract object is a concrete instance
- method
- Define and call
- Object reference
- Reference type: basic type (8)
- Objects are operated by reference: stack - > heap
- Attribute: field file member variable
- Default initialization:
- Number: 0.0
- char: u0000
- boolean: false
- Reference: null
- Modifier attribute type attribute name = attribute value
- Default initialization:
- Object creation and use
- You must use the new keyword to create an object, and you also need the constructor Person link= new Person();
- Object's property link name()
- Object sleep()
- class
- Static properties
- Dynamic behavior method
3. Packaging
- The dew that should be exposed, the hide that should be hidden
- Our program design should pursue "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by ourselves, and external interference is not allowed; low coupling: only a small number of methods are exposed for external use
- Encapsulation (data hiding)
- Generally, 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
- Property private get/set
Example: class private data / property setting public interface
package com.oop.demo04; //Class private public class Student { private String name;//name private int id;//Student number private char sex;//Gender private int age;//Age //Provide some methods that can manipulate this property //Provide some public get and set methods //get gets this data / property public String getName(){ return this.name; } //set sets a value for this data / property public void setName(String name){ this.name=name; } 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>150 || age<0){ this.age=3; }else { this.age = age; } } }
Example: object usage
package com.oop; import com.oop.demo04.Student; /* 1.Improve program security and protect data 2.Hidden code program details 3.Unified interface 4.Improve the maintainability of the system */ public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("pantheon "); System.out.println(s1.getName()); s1.setAge(999);//illegal System.out.println(s1.getAge()); } }
Output diagram
4. Succession
-
The essence of inheritance 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
-
In Java, classes only have single inheritance, not multiple inheritance (one parent, many children, one child, one parent)
-
Inheritance is a 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
Example: parent class
package com.oop.demo05; //In Java, all classes inherit Object directly or indirectly by default //Person: parent class public class Person /* extends Object */{ //public //private //default //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; } }
Example: subclass
package com.oop.demo05; //Student is person: derived class (subclass) //The child class inherits the parent class. Will have all the methods of the parent class public class Student extends Person{ //Ctrl+H open genealogy }
Example: Object Application
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()); } }
Output diagram
-
object class
-
super this
-
super note
- 1.super must call the constructor of the parent class in the first place of the constructor
- 2.super must only appear in subclass methods or constructor methods
- 3.super and this cannot call construction methods at the same time
-
this note:
-
Different representative objects:
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 inheritance conditions
-
Construction method
this(); Construction of this class
super(); Construction of parent class
-
Example: parent class
-
package com.oop.demo05; //In Java, all classes inherit Object directly or indirectly by default //Person: parent class public class Person /* extends Object */{ public Person() { System.out.println("Laastor has no participation"); } protected String name="Yatox"; public void print(){ System.out.println("Layast"); } }
Instance: subclass
package com.oop.demo05; //Student is person: derived class (subclass) //The child class inherits the parent class. Will have all the methods of the parent class public class Student extends Person{ public Student() { //Hidden code: the parameterless construction of the parent class is called //super(); The code that calls the constructor of the parent class must be in the first line of the code in the constructor of the child class System.out.println("Kaiyin parameterless construction is executed"); } private String name="Sword demon"; public void print(){ System.out.println("Kaiyin"); } public void test1(){ print(); this.print(); super.print(); } public void test2(String name){ System.out.println(name); System.out.println(this.name); System.out.println(super.name); } }
Example: Application
package com.oop; import com.oop.demo05.Student; public class Application { public static void main(String[] args) { Student student = new Student(); student.test2("Dark descendant"); student.test1(); } }
Output diagram
Method rewriting
Override: inheritance relationship is required. The subclass overrides the method of the parent class
1. The method name must be the same
2. The parameter list must be the same
3. Modifier:
The scope can be expanded but not reduced: public > protected > Default > private
4. Exceptions 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:
1. The function of the parent class and the subclass are not necessarily required or satisfied
Alt+Insert: overrideļ¼
Example: parent class
package com.oop.demo05; //Rewriting is the rewriting of methods, which has nothing to do with properties public class B { public void test(){ System.out.println("B-test"); } }
Example: subclass
package com.oop.demo05; //Inheritance relationship public class A extends B{ @Override public void test() { System.out.println("A-test"); } }
Example: Application
package com.oop; import com.oop.demo05.A; import com.oop.demo05.B; public class Application { //Static methods and non static methods are very different //Static method: the method call is only related to the data type defined on the left //Non static: override 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 //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 } }
Output diagram
5. Polymorphism
- That is, 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 reference types that can point to the object
- Conditions for the existence of polymorphism
- There is an inheritance relationship
- Subclass overrides parent method (method needs to be overridden)
- The parent class application points to the child class object
- be careful:
-
- Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
- Parent and child classes, with associated type conversion exception ClassCastException
-
Example: parent class
package com.oop.demo06; public class Person { public void run(){ System.out.println("Moisten"); } }
Example: subclass
package com.oop.demo06; public class Student extends Person{ @Override public void run() { System.out.println("God God"); } public void eat(){ System.out.println("eat"); } }
Example: Application
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 //All 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(); Object s3=new Student(); //The methods that can be executed by an object mainly depend on the type on the left of the object, which has little to do with the right s2.run();//The subclass overrides the method of the parent class and executes the method of the subclass s1.run(); } }
Output diagram
instance of
6.static keyword
Load with class
Example:
package com.oop.demo07; public class Student { private static int age;//Static variable private double score;//Non static variable public void run(){ } public static void go(){ } public static void main(String[] args) { Student s1 = new Student(); System.out.println(s1.score); System.out.println(Student.age); new Student().run(); Student.go(); } }
7. 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, that class is a modified class
- Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes
- Abstract class: you cannot use the new keyword to create an object. It is used to let subclasses inherit
- Abstract method: there is only the declaration of method, but no implementation of method. It is used to make subclasses implement
- If a subclass inherits an abstract class, it must implement the abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class
8. Interface
- Common class: only concrete implementation
- Abstract classes: both concrete implementations and specifications (abstract methods) exist
- Interface: specification only
- An interface is a specification. It defines a set of rules, which embodies the idea of "if you are... You must be able to..." in the real world. If you are an airplane, you must be able to fly. If you are a car, you must be able to run. If you are a helicopter, you must be able to split lightning and whirlwind.
- The essence of an interface is a contract, just like physical rules. Everyone abides by it
- Function of interface:
-
- constraint
-
- Define some methods for different people to implement
-
- The default methods in the interface are public abstract
-
- The attributes defined by the interface are constants public static final
-
- Interfaces cannot be instantiated (nor can abstract classes be instantiated); Because there is no constructor in the interface
-
- implements can implement multiple interfaces
-
- You must override the methods in the interface
-
Example: interface 1
package com.oop.demo09; //The keywords defined by interface and interfaces need to implement classes public interface UserService { //The attributes defined by the interface are constants public static final int age=99; //All defined methods in the interface are actually abstract. public abstract is provided by default void add(String name); void delete(String name); void update(String name); void query(String name); }
Example: interface 2
package com.oop.demo09; public interface TimeService { void time(); }
Example: implementation class of interface
package com.oop.demo09; //Abstract class: Extensions single inheritance //A class can implement the interface through implements //The class that implements the interface needs to rewrite the methods in the interface //Using interface to realize multi inheritance 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 time() { } }
9. Internal class (extension)
- Internal class is to define another class inside a class. For example, if a class B is defined in class A, class B is called internal class relative to class A, and class A is called external class relative to class B
-
- Member inner class
-
- Static inner class: use static as modifier
-
- Local internal class: create another class in a method in public class
-
- Anonymous inner class: there is no name to initialize the class, so there is no need to save the instance to the variable
Example: inner class
package com.oop.demo10; public class Outer { private int id=10086; 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); } } }
Example: Application
import com.oop.demo10.Outer; public class Application { public static void main(String[] args) { //The external class is implemented through the new keyword Outer outer = new Outer(); outer.out(); //Inner classes are instantiated by outer classes Outer.Inner inner = outer.new Inner(); inner.in(); inner.getID(); } }
Output diagram