MODULE 5 OOP object-oriented programming
--------------------------------------------------------
Object Oriented programming abbreviation
Class/object Object
--------------------
All things are objects
Class: A combination of a set of objects with the same properties and behavior
Class Name {
Property
Constructors
Method
}
Object: An instance of a class
New class name
Three major features of OOP
1. Package Encapsulation
Purpose of encapsulation: to realize the hiding of information
1) Hiding the property information of the object
2) Concealment of the implementation details of the behavior
External users do not need to focus on the implementation details of the method
2.Inheritance inheritance
The relationship between classes and classes
1) There is a certain similarity between the objects
2) The semantic relationship of "is a" must be satisfied between the subclass and the parent class
Child class is a parent class
Cat is a Animal
Summarize:
Usually the parent class represents a large group, and subclasses are small groups in this large group.
3, polymorphic polymorhism
The same behavior, different objects have different implementations
Method definitions in Java
--------------------------
1) A method allows the presence of multiple modifiers, with no order of precedence between multiple modifiers
2) The return type is located after the modifier, and a method must have a return type
For methods that do not return a value, the return type is void
3) When there is a return value in the method, each branch in the method is required to have a return to ensure that there is a return value in either case
4) The parameters of the method can be 0~ multiple
Access to methods in the same class can be called directly
Method definition: Be sure to specify the parameter type
Method call: Parameter receives external data
5) The constructor is not a normal method, the constructor and the normal method call mechanism is different
Parameter passing *
-----------------------
Distinguishing between formal parameters and arguments
Parameters: Parameter When method is defined, not explicitly evaluated
Arguments: Explicit values passed to formal parameters when a method is called
Argument----> Parameters
1. Parameters are basic data types
Pass value, copy the value of the argument to the formal parameter
2. Parameter is a reference type
A reference is a copy of the address of the referenced object to a parameter
this keyword
-------------------
Attribute:name gender age represents a member variable
Paired accessors: An operation for assigning and taking a value on a property
public void SetName (String name) {name=name;}
According to the nearest principle, the local variable name is found
This represents the current class or object
When the member variable name is the same as the local variable name, this is used to differentiate
public void SetName (String name) {this.name=name;}
Packaging
--------------------
1) Hiding Property information
Add the private modifier before the property, which represents access only within the class
Provide access to the external child, you can access the sub-constrained attributes of the reasonable range of values
Method overload overloading
-----------------------
Conditions:
1) inside of the same class
2) defines multiple methods with the same name
3) different parameter types or numbers
4) return type does not require (can be same or different)
Advantage: External users often do not pay attention to the method of invocation, by the compiler's own judgment
Creating and Initializing objects
---------------------------
Created object: New Student ();
1) to open up space for the object;
2) default initialization for member variables of an object (0/false/null)
3) Explicit initialization
Class student{
String name= "Zhan";
int age=23;
}
Cons: Each time an object is created, the property values are the same
4) Constructors
When the property value of an object is indeterminate, the constructor gives you the flexibility to control
Role:
Initialization of attributes does not involve complex logic code
Allows multiple constructors to be defined, providing multiple initialization scenarios
Knowledge Points:
1) There must be a constructor in the class
2) The user does not explicitly define the constructor Java will assign the parameterless constructor by default
Public Student () {}
3) Once the constructor is explicitly defined by the user, no parameterless constructor is assigned
How do I call another constructor in one constructor?
Purpose: Simplify code
Use the This keyword
This (Name,gender);
Attention:
1) Call another constructor with this (...) ) can simplify the code
2) The This () statement in the construction method must be the first statement
Summarize the two uses of this:
1) The local variable names of the member variables and methods are simultaneously
public void SetName (String name) {this.name=name;}
2) When the constructor overloads, call another constructor
This (param_list);
Inherit inheritance
--------------------------
Essential Purpose: To implement code reuse
Syntax: classs subclass extends superclass{...}
Significance:
1) subclass inherits properties and methods of parent class
2) Subclasses can add attributes and behaviors that are unique to them
Conditions to satisfy inheritance:
1) "is a" relationship
2) Inheritance in Java can only be single inheritance, subclasses can have only one parent class
Class A extends B,c//error
What grammatical components of the parent class are inherited by the quilt class?
--------------------------------------
1) The properties of the parent class and non-private methods can be inherited by the quilt class
The private property of the parent class that the subclass can access only by accessing the child
2) The construction method of the parent class cannot inherit from the quilt class, but the subclass must call the parent class constructor
Invocation of the parent class constructor
1) Implicit invocation
There is no super (...) in the subclass. When you explicitly call the parent class constructor, the child class calls the parent class's parameterless constructor by default
2) Explicit invocation
If there is no default parameterless constructor in the parent class, the subclass constructor must explicitly call the parent class's constructor method
Syntax: Super (param_list);
Parameter types must match the parent class constructor
The statement must be executed in the first sentence
Super keyword
------------
Super represents the parent class
1) When a subclass calls a method with the same name as the parent class
Super.setage (age);
2) constructor method for calling the parent class in the subclass constructor
Super (Param_list);
Polymorphic polymorphism
--------------------------
For different objects, the same behavior causes different results, and the program dynamically determines which object and its methods are called at run time
Static type
Person p; The type of P has been determined
Dynamic type
New Student (); When the program runs
P can represent either the person object itself or its subclass object
P=new person (); P.display (); methods in//person
P=new Student (); P.display (); methods in//student
Three conditions for polymorphic presence:
1) must have a subclass to inherit the parent class;
2) Be sure to have subclasses overriding the parent class with the same name method, i.e. overriding
3) The reference of the parent class to the object of the child class
Casting Coercion Type conversions
--------------------------
Forced type conversions are required when large types are assigned to small types
Syntax: (target type of conversion) the variable to be converted
How can I avoid any type conversions?
------------------------------
For example:
Animal a=new Bird ();
Cat c= (CAT) a;//classcastexcption type conversion error
Cannot convert bird type object to cat type
Operator instanceof
---------------------------
Comparison operator with the result of True/false
Usage: reference-type variable instanceof class name
Function: Determine whether the dynamic type of the object that the preceding reference variable actually points to is the following class itself or its subclass, which returns true, otherwise false
Typically, the reference type is casting, and the instanceof should be used first for type determination
Method rewrite/Overwrite overriding
-------------------------------------
1) must be between subclass and parent class (different from overloading)
2) Method Name: Both the parameter list and the return type are the same;
3) Visible range cannot be reduced
A method with the same name as the subclass must not be less accessible than the parent class's method access permission
4) throws the exception cannot enlarge the quilt class
That is, the exception that the subclass method throws must be the same as the exception that is thrown by the parent class method, or the subclass of the exception class that the parent method throws
Class super{
public void Method () throws ioexception{}
}
Class Sub extends super{
public void Method () throws exception{}
}
MODULE 6 Advanced language Features
---------------------------------------------------
Focus:
1.static keyword-Modified variable method initializes a block of code
2.final keyword-Modified class method variables
3. Access rights control public protected default (package private) private
4. "= =" and equals () comparison
5. Abstract classes and Interfaces *
6. Internal class *
7. Set Frame collection**
8. Reflection Mechanism reflection**
static modifier
-----------------------------
1. Modifying variables-----Static variables
----can only modify member variables, cannot modify local variables
Feature: All objects of this class are shared
static int maxage=120;
1) Static is similar to a global variable in some way
2) Syntax: class name. Static variable Name
P1.name access to normal member variables
Person.maxage access to static variables
2. Modification methods---static methods
Characteristics:
1) All objects of this class share this method
2) cannot access non-static syntactic components (normal method/member variables), only static variables and static methods can be accessed
3) to access the normal methods and member variables of a class in a static method, you must first create the instantiated object of the class
Methods that only manipulate static variables and do not manipulate member variables are typically defined as static variable methods
4) static methods in the parent class cannot be overridden by a quilt class as non-static
(That is, the quilt class must be covered as a static method)
5) Generally, the tool classes in Java provide static methods
3.static decorated initialization code block
----Static code block
Can write code in the method outside, must use static{...} Enclosed.
Class a{
static{
Code, no method name can be called
}
}
1) can only be executed once, at the time of class load (loaded in memory) one-time execution
2) multiple static blocks of code can exist, and the JVM will meet and execute
3) constructors that take precedence over classes
Usually for static variables that require only one-time initialization, not written in the constructor, but with static blocks of code
Final keyword
-----------------------
Features: Non-change sex
1. Modifier Variables----Constants
Once assigned, you can no longer modify
2. Modification methods
This method can only be inherited in subclasses, but cannot be overridden overriden
3. Modifier class
Cannot have subclasses inheriting final class
Final Class a{}
Class B extends a{}//illegal
The class is final, the class no longer has subclasses, and the method inside means that it cannot be overridden, equivalent to the method final
Static Final-----------constant
Access CONTROL permission controls
------------------------------------
Public common, maximum access rights
Protected a subclass in the same package or in another package can access the
(Package private) The classes in the same bundle can be accessed
Private, accessible only within this class
Public > Protected > Package Private > Private
Object
----------------------
The default ancestor class in Java, object is the root of all classes, and a single-inherited parent will eventually hang in the Object class
Class A (extends Object) {}
1.toString ()
Returns a string that describes the property information for an object
Class person{
String toString () {
return name;
}
}
Usage: Person p=new person ();
SYSTEM.OUT.PRINTLN (P);//Default Call P.tostring ()
System.out.println (P.display ());//when P is null Yes, error
Comparison of "= =" and Equals ()
------------------------
1. "= ="
Typically used to compare basic data types----comparison values
If the reference type is compared--------the reference address is compared
Person P1=new person ();
Person P2=new person ();
P1==p2? False two references point to not the same object
P1=P2;
Pq==p2? True P1 and P2 point to the same object
2.equals (Object obj)
P1.equals (p2); Compare two objects with the same type and content
1) classes provided by Java, for example, String
By default to implement the Equals () method, you can directly invoke the comparison of objects
2) for a custom class, be sure to override the Equals () method
public boolean equals (Object obj) {
1. If the comparison type is the same, use instanceof
2. Compare each property to the same value
3. Return true only if the type and content are the same;
}
The code is as follows:---------------------------------------------------------------------------------------------
public boolean equals (Object obj) {
if (obj instanceof person) {
Person p;
p= (person) obj;//coercion type conversion
if ((This.getname () ==p.getname ()) && (This.getsex () ==p.getsex ()) && (This.getage () ==p.getage ())) {
return true;
}
else return false;
}
else return false;
}
Or:----------------------------------------------------------------------------------------------------------
public boolean equals (Object obj) {
if (obj instanceof person) {
Person p;
p= (person) obj;//coercion type conversion
if (This.getname () Equals (P.getname ())) && (This.getsex (). Equals (P.getsex ())) && (this.getage () = = P.getage ())) {
return true;
}
else return false;
}
else return false;
}
Wrapper classes wrapper class
--------------------------------
Provides wrapper classes for four classes of eight basic data types
1) Facilitate the operation of the design object
2) provides a conversion method between numeric and string types
3) The data types stored in the collection are reference types and do not support basic data type storage
Usage:
1.jdk1.5 Pre-loading/unpacking
Boxing: Basic data Type--reference type
int i=20;
Integer inte=new integer (i);
Unboxing: Reference type--basic data type
int J=inte.intvalue (); ==> j=20
Automatic packing/unpacking after 2.jdk1.5
Packing:
Integer inte=30;
Unpacking:
int i=new Integer (5); ==> i=5
int j=inte;
On either side of the assignment number, one side is the base data type, one side can be the wrapper class
Abstract classes and abstract methods
--------------------------------------
Abstract class
Abstract class a{}
Real-World Object---------(abstract)----------> class
Class---------> (abstract)------> abstract class
Cat class Dog Class ===> animal abstract class
Characteristics:
1) Cannot instantiate object (cannot use new operator)
Animal a=new Animal ();//illegal
Animal A; Legal
A=new Cat ();
A=new Dog (); Legal
Design Purpose:
Using the abstract class's reference variable to manipulate its subclass object;
2) and sub-class satisfies "is a" semantic relationship;
3) Single Inheritance
Abstract methods
Abstract class a{
abstract void method ();
}
Characteristics:
There is no concrete implementation of the method, only the declaration of the method
Design Purpose:
A specification is typically defined that represents the behavior that all subclasses must have, requiring subclasses to provide a concrete implementation of the behavior
Knowledge Points:
1) classes that have abstract methods must be declared as abstract classes
2) Abstract classes can have 0~ multiple abstract methods, can also have a common method
3) Subclasses must provide implementations of abstract methods in abstract classes
4) Abstract classes can inherit abstract classes, abstract classes cannot inherit ordinary classes
Class-Specific inheritance Abstraction
5) Abstract cannot co-decorate a class with final (cannot instantiate object, cannot inherit class--useless)
6) There are constructors in abstract classes
Call to Subclass
Thinking: Fish Animal Food
Interface interface
-----------------------
To implement multiple inheritance indirectly
Definition: Public interface interface Name {}
Characteristics:
1) An object cannot be instantiated, another form of an abstract class
2) syntax elements in the interface:
A) The variables in the interface are static constants (static final writes are not written by default)
b) The methods in the interface are abstract (the abstract write is not written by default)
public interface a{
int abc=100;
public void Method ();
}
Defines a specification of a behavior that the implementation class of an interface must provide a concrete implementation of, which can have no correlation between the implementation classes
Cat Dog Bird Animal Plane
public interface flable{
publi void Fly ();
}
Class Bird extends Animal implements flable{
public void Eat () {...}
public void Fly () {...}
}
c) No constructor exists
3) interface and interface and the legal relationship between the interface and the class
A) class implements interfaces that can implement multiple interfaces
Class A implements b,c{}
A class can inherit both classes to implement multiple interfaces
b) Interfaces can inherit multiple interfaces
Public interface C extends a,b{}
The difference between an abstract class and an interface
---------------------------
Similarities:
1) can not be instantiated
2) Abstract methods can only be declared as not implemented, all represent a code of conduct
3) Subclasses or implementation classes must provide implementations of abstract methods
Design angle:
is to have the reference variable of the parent class or interface point to the child class or to the object of the implementation class
Different places:
1. Grammatical angle
Keyword Abstract class interface
--------------------------------------------------------------------------
Variable member variable/static variable/final only static constant
Method Common Method/abstract method only abstract method
The constructor exists, and you can customize the non-existent
2. Programming ideas (design concept)
The semantic relationship satisfies "is a" without
Abstraction of the abstract behavior of a class
(Generalization of the public part of a subclass) implements no association between classes
Practice:
Custom classes to implement additions and deletions to multiple objects as arrays and traversal operations
The data structure is managed in a linear manner (accessed by index number)
Inner class inner class
--------------------------
Class a{
int i;
void method () {}
Class b{
Int J;
void print () {}
}
}
To define a class within another class
Design Purpose:
1) Reduce naming conflicts, and you can define classes with the same name in different classes
Internal classes carry external information
2) Reduce the scope of use of the class, so that its use is smaller than the package, can be within a class inside or inside a method or even the internal use of the expression
Precise determination of the scope of use of the class
3) Internal classes can access the private syntax components of external classes
Main functions:
Precise control of the use of the class range
How do I avoid instantiating an inner class object multiple times?
Anonymous inner class, control inner class can only be used once
The definition and use of internal classes are usually put together
New engine () {//borrow the name of the parent class or interface to create an inner class
void produce () {}
};//don't forget the semicolon behind the curly braces.
Classification of inner classes:
----------------------------
1. Static Inner class
Reference static method or static member variable
Class outer{
private static int i;
static void Method () {}
Static Class inner{
public void Method () {
i++;//can access static syntax components
Out.method (); Methods for accessing external classes
}
}
}
Characteristics:
1) defined within the class, accessible within the class
2) independent of external class objects, can be built independently
3) only static syntax components of external classes can be accessed
Usage:
1) How is it created inside an external class?
Inner inn=new Inner (); Same as normal class object creation
2) How is the external class created outside?
Condition: Inner class non-private
Outer.Inner oitest=new Outer.Inner (); To create an object of an inner class
Outer o=new Outer (); This statement creates only the Outer class object, and the inner class object needs to be created independently
2. member Inner class
Refer to common member variables and methods
1) defined inside the class, outside of the method
2) The inner class of the member is closely dependent on the external Outer class object (different from the static inner Class).
3) access to all syntactic components in the external class, including private
Usage:
1) Create an inner class object inside the outer class
Inner inn=new Inner ();
2) Create an inner class object outside the outer class
Ordinary member variables and methods are closely dependent on the object of the class, you must first create the object, and then access other properties and methods, the member inner class is the same
Out.inner oinn= (New Outer ()). New Out.inner ();
3. Local inner class
Further narrowing of the scope of use, used only within the method
1) defined within the method, refer to local variables
2) access to all syntactic components of the external class
3) Only the "local constant" where it resides can be accessed
4) cannot add public/protected/private/static modifier, no meaning
Similar to local variables, only used inside methods
4. Anonymous inner class
No class name
Class outer{
public void Method () {
Class Inner implements iinterface{
void method () {}
}
Inner inn=new Inner ();
}
}
1) also defined within the method
2) No class name, no constructor, no class/extends/implements keyword
Borrow the name of its parent class or interface
3) Use and definition are put together and used at once
Reform:
Class outer{
public void Method () {
IInterface inn=new IInterface () {
void method () {}
};
}
}
Transformation process:
1) Delete the Class/extends/implements and class names
2) When creating an object, use the name of the parent class or interface instead of the object that created the class:
A a=new a (); To create an object of Class A
A a=new a () {...};
A) A is a class: Creates an anonymous subclass object of Class A
b) A is an interface: an object that creates an anonymous implementation class for interface a
Collection Collection Framework * *
------------------------------------
The collection framework in Java is semi-finished and can be used for two development
---provides a common implementation of data structures for storing and managing multiple objects
1) will look at the API
2) Understand the characteristics of common data structures
3) ability to increase and revise the various sets of classes to check operations
Characteristics:
The classes in the collection are used to store multiple objects (only object types)
Package: Java.util;
Interface:
1.Collection interface Storage manages a set of objects without dependencies
|-------list interface data is stored sequentially, accessed by index number, allows object duplication, and allows null
| The data stored-------the set interface is unordered and does not allow duplication
|------The SortedSet interface has the sort function set
2.Map interface manages a pair of objects in the form of key-value pairs (key~value)
|------SORTEDMAP interface provides a map with sort function
Problem:
1) How can I tell if the stored object is duplicated in set? Is it enough to rewrite equals ()?
2) SortedSet provides a sort of function, then according to what to sort?
For example: Students (school number, name, score, age), each attribute can be sorted,
Require developers to specify rules for sorting
Implemented:
Collection no Implementation class
List Implementation Class
ArrayList uses arrays to store a set of objects, access the data according to the index number, and delete the inefficient, find efficient
LinkedList adopt the way of doubly linked list, can only provide from the previous or from the back to the order to find elements, delete efficient, find inefficient
Vector Thread-Safe ArrayList
Set Implementation Class
HashSet Data No order, no repetition
SortedSet Implementation Class
TreeSet provides a set of sort functions
List exercises:
Create a bank account class accounts
attribute: int code;
String name;
Double balance;
Method: Override the ToString () method to return the account information
Create Listtest.java use ArrayList to add and remove a set of accounts and print out all account information in the list
Set Exercise:
Create Settest.java use HashSet to operate a group of accounts, put in some duplicate accounts, verify that duplicate data is successfully placed in
The element holding mechanism in set:
According to the Hashtable hash algorithm, the numerical value is the remainder of the table length, then the object?
How do I get the unique int type data on the object?
The Hashcode () method in object:
Returns the hash code of the object
To determine whether two objects are the same in set, you need to override the Equals () and Hashcode () two methods
Iterator iterators
-------------------------------
It provides a unified traversal algorithm for different data structures, and solves the traversal problem
public interface iterator{
public boolean hasnext ();
Public Object next ();
public void Remove ();
}
iterator{
}
Class arraylist{//This little program is important.
...
Public Iterator Iterator () {//anonymous inner class
return new Iterator () {
public Boolean hasnext () {...}
Public Object Next () {...}
public void Remove () {...}
};
}
...
}
Take ArrayList as an example to implement traversal:
List list=new ArrayList ();
Iterator Iter=list.iterator ();
while (Iter.hasnext ()) {
System.out.println (Iter.next ());
}
Iterators are only available for collection branches, not for map branches
Comparator Comparator
-------------------------
Specify a comparison rule between objects
Public Interface comparator{
public int Compare (Obiject o1,object O2);
public boolean equals (Object O);
}
public class Codecomparator implements comparator{
public int Compare (Object o1,object O2) {
Compare the code properties of O1 and O2
}
}
Compare method:
If the returned result is >0, the O1>o2
If the returned result is <0, the O1<o2
If the returned result = 0, the O1=o2
Set set=new TreeSet ();
Exercise: Using TREESET data structures to manage a set of account requirements:
1) The account is provided in the form of a code row
2) The account is provided in the way of balance inverted
Map
----------------------
Store and manage a set of objects in a key-value pair, one key corresponding to a value
Key ~ Value
Example: Student:code ~ Student
Key value: Unique non-repeating key value is also an object of type objects
Value: Can be repeated also object type
Map.entry: An association of key and value, also object type
The implementation class of Map
Hashtable Thread Safety
HashMap Thread Insecure hashtable
Implementation class of SortedMap
TreeMap added the sorting function
Exercise: Create a Maptest test class that stores a set of account (Code,name,balance)
Set KeySet () gets a collection of all the key objects in the map
Collection values () gets a collection of all the value objects in the map
Set EntrySet () gets a collection of mapping relationship objects for all key~value in the map
Reflection Reflex * * *
--------------------------------
Class----> Mirroring
People----> Mirrors
Syntax elements in class:
Package information
Import information
public class class name Extends/implements parent class/interface {
Member variables: modifiers, data types, identifiers
Common methods: modifiers, return types, identifiers, argument lists, exceptions
Constructor: modifier, parameter list
}
Package: Java.lang.reflect;
Import Required
Mirroring of classes
Java.lang.Class
Mirroring of member variables
Java.lang.reflect.Field
Image of the method
Java.lang.reflect.Method
Image of the constructor
Java.lang.reflect.Constructor
A a=new a ();//Create Object A of Class A
String classname= "A";
The core of the reflection mechanism:
Dynamically acquire information about the class class of a known name at run time, create the class dynamically (call the constructor), and invoke its methods or modifier properties (even private properties and methods)
Introspection: Introspection/vipassana, ability to see through class
Application of Reflection mechanism:
1) The original construction information of the class can be obtained by mirroring
2) Dynamically create the object of the class (not at compile time) with the class name while the program is running
Widely referenced in the framework
3) Destroy package: The class's member variable/method/constructor can be obtained by reflection. Private properties
How to get the image of a class
--------------------------
1) If you know the class name, get the image of the class based on the class name. class
Class c=string.class;//c represents a mirror image of the String class
Class C1=INT.CLASS;//C1 represents the image of the int base data type
2) Only the reference variable is known, the GetClass () method of the calling variable
String str= "ABC";
Class C=str.getclass ();//c represents a mirror image of the String class
3) only know the class name given in string form
Class.forName ("class name");
String classname= "java.lang.String";
Class.forName (classname);
There's no way to declared.
Example: GetFields () GetMethods ().
Returns the Public property or method in the class or interface represented by the class object, including inheritance
A method with declared
Example: Getdeclaredfiedlds () getdeclaredmethods () ...
Returns all properties or methods (Public/protected/default/private), but does not include inherited properties and methods
Practice:
The class name represented by a data structure (Collection) is passed through the command line, which dynamically creates the object of the Class (New ArrayList ()) through the reflection mechanism, puts several objects into the data structure, and then traverses the object information in the output data structure.
Example: "Java.util.ArrayList"---> Args--args[0]
Analysis:
1) Get the mirror of the class represented by Args[0]
Class C=class.forname (args[0]);
2) Create an instantiated object for this class
Object o=c.newinstance ();
3) o---> Collection----> O.add (...);
The Newinstance () method invokes a public and parameterless constructor for the class
Practice:
Define a Data.java class so that the syntax components are private
Data d=new data ()//Cannot create an object of this class externally (because the constructor is private)
Through the reflection mechanism:
1) Create an instantiated object for this class
Gets the mirror data.class of the class;
Gets the constructor image of the class c.getdeclaredconstructors ();
Opens the constructor as a common con.setaccessible (true);
2) Call the private method within
3) Modifier Property value
Core Java 5~6 (OOP & Advanced language Features)