Object-oriented development technology 05_Messages, instances and initialization
Object-oriented development technology 05_Messages, instances and initialization
05 Messages, instances and initialization
1.Message
A way for objects to request or collaborate with eachother.
object-oriented message model
- Objects are communication entities that communicate with each other by passing messages. They can both receive and reject messages from the outside world.
The object receives messages it recognizes
and rejects messages it does not recognize.
Objects cannot interact with other objects in unpredictable or previously disallowed ways
The process of sending messages
Consider object A sending a message to object B, which can also be seen as object A requesting services from object B.
- Object A needs to know clearly what kind of services object B provides.
- Depending on the requested service, Object A may need to give Object B some additional information so that Object B knows exactly how to handle the service.
- Object B can feed back the final execution results in the form of a report
Messaging syntax
- Message → Receiver.
- Response behavior varies from receiver to receiver.
2. Static and dynamic languages
Dynamically/statically typed language
- Dynamically Typed Language: Variables are regarded as name identifiers, and types and values are associated
- Type checking is done at runtime ;
- Generally, there is no need to declare the variable type before using it, and the type of the variable is usually determined by the type of the value being assigned .
- The advantage is that it is easy to read and does not require writing a lot of type-related code.
- The disadvantage is that it is inconvenient to debug . If the naming is not standardized, it will cause incomprehension and is not conducive to understanding.
- Such as php, Python and Ruby.
- Statically Typed Language: Types and variables are linked together
- Type checking is done at compile time .
- At compile time, the type of language needs to be determined. That is, you need to explicitly declare the variable type when writing a program.
- Such as C/C++, Java, C#, etc.
- The advantage is that its structure is very standardized, easy to debug, and convenient for type safety;
- The disadvantage is that more type-related code needs to be written for this, which makes it inconvenient to read and unclear.
- Memory allocation decisions are made at compile time. No need to run time reallocation.
- Wrong control type.
Object-oriented static
C++, Delphi pascal, Eiffel, Java
Object-oriented dynamic
Objective-c, Smalltalk, Dylan, Python
non-object-oriented static
Ada, Algol, C, Fortran, Haskell, ML, Modula
non-object-oriented dynamic
APL, Forth, Lisp, Prolog,Snobol
The difference between dynamically typed languages and statically typed languages is whether variables or values have the characteristic of type.
dummy variable
- In most object-oriented languages, the receiver does not appear in the parameter list of the method, but is hidden in the definition of the method. Pseudo-variables are used only when the receiver value must be accessed from within the method body .
- A pseudo variable is very similar to a normal variable, except that it does not need to be declared and cannot be changed (perhaps the term pseudo constant is more appropriate, but this term does not seem to appear in the definition of any language)
Java, C++: this
Eiffel: Current
Smalltalk, object-c: self
Pseudo variables are used as if they were instances of a class. ** In many programming languages, the use of receiver dummy variables can be ignored.
- In many programming languages, the use of receiver dummy variables can be ignored. ** If a data field is accessed or a method is called without referring to the receiver, then this means that Receiver dummy variables will be used as the body of the message .
Use of this in Java
- Use the this keyword to refer to member variables
- Use the this keyword to refer to other constructor methods within their own constructor method
- Use the this keyword to refer to member methods
- Using the this keyword to represent objects of its own class
Referencing Member Variables with the this Keyword
Inside a class's method or constructor method, you can refer to a member variable name using the format "this.member variable name", which can be omitted in some cases and cannot be omitted in others
public class ReferenceVariable {
private int a;
public ReferenceVariable(int a){
this.a = a;
}
public int getA(){
return a;
}
public void setA(int a){
this.a = a;
}
}
The java language specifies that when variables have overlapping scopes, the variable with the smaller scope overrides the variable with the larger scope . So inside the constructor and setA methods, the parameter a acts .
So if you access member variable a you must reference it with this.
referencing constructor methods
public class ThisTest {
private int i=0; // The first constructor: has a String-type formal parameter.
// first constructor: has a String formal parameter
ThisTest(String s){
System.out.println("String constructor: " + s);
}
// Second constructor: has an int and a String formal parameter
ThisTest(int i,String s){
this(s);// this calls the first constructor
this.i=i++;//this to reference the member variables of the class
System.out.println("Int constructor: "+i+"/n "+"String constructor: "+s);
}
Note:
- No other method can call a constructor, ** only a constructor method can call ** it.
- Even if a constructor is invoked by a constructor method, it must be on its first line and the constructor method can only invoke the constructor one and only once!
Using the this keyword to represent an object of its own class
public class ThisTest {
private int i=0; //first constructor: has a formal parameter of type int
//first constructor: has an int formal parameter
ThisTest(int i){
this.i=i+1;//this is a reference to the member variable i, not the function parameter i
System.out.println("Int constructor i--this.i: "+i+"--"+this.i);
System.out.println("i-1: "+(i-1)+"this.i+1: "+(this.i+1));
// It is well proven from the two outputs that i and this.i are not the same!
}
public ThisTest increment(){
this.i++.
return this;//returns the current object, which belongs to (ThisTest)
}
public static void main(String[] args){
ThisTest t0=new ThisTest(10);
System.out.println(t0.increment().increment().increment().i);
//t0.increment() returns a ThisTest object with i++ on top of t0.
// Then it returns a ThisTest object with i++ on top of the object returned above!
}
}
** Java:Constructors use this to distinguish between parameters and data members. **
3. Object creation
Instance of a class
** An object belonging to a class is called an instance of that class.
- An object has an instance-of relationship with its class.
- An instance is an object created from a class
- A class describes the behavior (methods) and structure (properties) of the instance.
Classes and instances have the following characteristics
- Different instances of the same class have the same data structure, are subject to the same operations defined by the same set of methods, and thus have the same behavior.
- different instances of the same class can hold different values, and thus ** can have different states
- The initial state (initial value) of an instance ** can be determined in instantiation
Object = state (instance variable) + behavior (method)
- Outside the object, clients can only see the behavior of the object; inside the object, methods provide appropriate behavior by modifying the state of the object and interacting with other objects
Memory partitioning: at the beginning of object creation
public class ClassDemo02 {
public static void main(String args[]){
Person per = new Person() ;
}
}
public class ClassDemo03 {
public static void main(String args[]){
Person per = new Person() ;
per.name = "ZhangSan" ; // Assign a value to the attribute.
per.age = 30 ;// call per.tell() ; // call per = new Person() ; // assign value to attribute
per.tell() ; // Call the methods in the class.
}
}
The case of declaring multiple variables:
public class ClassDemo04 {
public static void main(String args[]) {
Person per1 = null; // declare per1 object
Person per2 = null; // declare per2 object
per1 = new Person(); // instantiate the per1 object
per2 = new Person(); // instantiate the per2 object
per1.name = "Zhangsan"; // Set the contents of the name property of the per1 object
per1.age = 30; // Set the content of the age property of the per1 object
per2.name = "Li4"; // Set the contents of the name property of the per2 object.
per2.age = 33; // set the content of the per2 object's age property
System.out.print("Content in per1 object --> ") ;
per1.tell(); // per1 calls the method
System.out.print("Content in per2 object --> ") ;
per2.tell(); // per2 calls the method
}
}
public class ClassDemo05 {
public static void main(String args[]) {
Person per1 = null; // declare per1 object
Person per2 = null; // declare per2 object
per1 = new Person(); // Instantiate only per1 object
per2 = per1 ;// give per2 access to per1's heap memory space
per1.name = "Zhangsan"; // Set the contents of the name attribute of the per1 object.
per1.age = 30; // set the contents of the per1 object's age attribute
// Set the contents of the per2 object, which in effect sets the contents of the per1 object
per2.age = 33; // set the contents of the per2 object, in effect setting the contents of the per1 object.
System.out.print("Content in per1 object --> ") ;
per1.tell(); // call the method in the class
System.out.print("Content in per2 object --> ") ;
per2.tell();
}
}
Object Creation
- Variable declaration combined with initialization
PlayingCard aCard = new PlayingCard(Diamond, 3);
- Separation of variable declaration and creation
- A variable declaration simply creates a name that identifies the variable.
- In order to create an object, the programmer must perform another operation. Usually this operation is represented by the new operator
Object Array Creation
- allocation and creation of arrays
- allocation and creation of objects contained in an array
C++:Combining
Objects are initialized using the default constructor.
Arrays are composed of objects and each object is initialized using the default (i.e., parameterless) constructor.
PlayingCard *cardArray[52];
_Java:new only creates arrays. Arrays contain objects that must be created independently. _
PlayingCard cardArray[ ] = new PlayingCard[13];
for (int i = 0; i < 13; i++)
cardArray[i] = new PlayingCard(Spade,i+1);
4. Memory Allocation and Recycling
Pointers and memory allocation
**Java without pointers? **
- All object-oriented languages use pointers in their underlying representations, but not all languages expose them to the programmer.
- Sometimes people use the phrase "Java has no pointers" as a comparison between Java and C++, but it is more accurate to say that Java has no pointers that are visible to the programmer because all object references are actually pointers that exist in the internal representation.
- ** Object references are actually pointers that exist in the internal representation **.
- Person x = new Person();// This contains a variable x. Yes, this reference variable is, in essence, a pointer!
Pointer Problems
- Pointer references heap allocated memory. Pointer variable survival?
For the value of a heap-allocated variable, it persists as long as a reference to it exists, so ** the survival of the value of a variable is generally longer than the survival of the process that created it** .
- Heap-allocated memory must be reclaimed in some way.
- There is a difference between pointers and traditional variables in some languages.
Memory Reclamation
- Created with new - heap memory
- Heap memory is not bound at the entry and exit of the procedure.
- Limited memory
public class ClassDemo06 {
public static void main(String args[]) {
Person per1 = null; // declare a per1 object
Person per2 = null; // declare a per2 object
per1 = new Person(); // instantiate a per1 object
per2 = new Person() ; // instantiate a per2 object
per1.name = "Zhangsan"; // set the contents of per1's name property
per1.age = 30; // Set per1's age attribute.
per2.name = "Li Si" ; // set the contents of per2's name property
per2.age = 33 ; // set the content of per2's age attribute
per2 = per1 ; // pass a reference to per1 to per2
System.out.print("Content in per1 object --> ") ;
per1.tell(); // call the method in the class
System.out.print("Content in per2 object --> ") ;
per2.tell();
}
}
Memory Recycling - Recycling Strategies
- Objects that are no longer used in a program are reclaimed using memory reclamation.
C++:delete
Object Pascal:free
- Garbage collection mechanism (Java, C#, Smalltalk)
- Always monitor the operation of the object, when the object is no longer in use, automatically reclaim the memory occupied by it.
- Usually works when ** memory is about to run out **.
Compare
Costs extra:
- Need to hang the executing application; after reclaiming, the program resumes execution
- Avoid releasing multiple times; avoid using freed memory; avoid running out of memory.
Static Data Fields/Static Data Members
** A public data field that is shared by all instances of a class. **
Java and C++ use the modifier static to create shared data fields.
Java:Initialization of static data fields is done by executing static blocks when the class is loaded.
static keyword
1. Modifying data members with static
Data members modified with static keyword are called static data members/static data fields/static variables/class members , also known as static members (global members) .
static Data type Data member name.
Class Name. Static members.
**static cannot modify local variables! **
2. Modifying member methods with static
Member methods modified with the static keyword are class methods/static member methods , class methods can be called directly by the class.
The calling relationship between static methods and non-static methods, static data members and non-static data members:
! Object-oriented development technology 05_Messages, instances and initialization
Conclusion: static members exist without instantiation , whereas non-static members are members that come after instantiation , and non-static members do not exist until they are instantiated. Thus it is possible to access a universally existing object using an object that exists only at one point in time; and it is not possible to access an object that exists only at one point in time using a universally existing object.
Data fields of a class (static data fields)
Objects themselves** do not initialize** shared fields. The memory manager automatically initializes the shared data to a particular value, and each instance goes to test that particular value. The first one to test does the initialization.
- In Java, initialization of static data fields is done by executing a static block when the class is loaded.
- Static data fields (static variables), along with static methods, are created after the class ** is loaded from disk into memory ** , ** exists and dies ** at the same time as the class.
- Static variables, also called **class variables , are **global variables in a class and can be called by all methods in the class .
- As long as this class is loaded, the Java virtual machine can find them by default in the method area of the runtime data area based on the class name . based on the class name . Therefore, a static object can be accessed before any of its objects are created, without referencing any objects . The following is a list of initialization values for various types of variables: the class name .
All static data members can be accessed within the class using direct access.
Static member function (class method)
- member functions. Cannot access non-static members .
- No this
- Constructors and destructors cannot be static members .
Static methods and instance methods
- Methods modified with static are called static methods
- Methods called using instance objects are called instance methods
5.Constructor
Initialize newly created objects.
- Advantages: Ensure that it will not be used before initialization, preventing multiple calls
When creation and initialization are separated (when using a programming language without constructors), it is easy for the programmer to forget to call the initialization routine after creating the new object, often with undesirable consequences.
- Java/C++: name, return value
- Data fields in Java and C# can be initialized to specific values .
- Another subtle difference between constructors and ordinary methods is that the constructor does not declare the data type of the return value.
- Constructor overloading: Allows multiple functions to be defined with the same name as long as the number, type, or order of each function's parameters are different
class Complex { // complex numbers
public Complex (double rv) { realPart = rv; }
public double realPart = 0.0; // initialize data areas
public double imagPart = 0.0; // to zero
}
Be sure to keep the following points in mind when declaring a constructor:
- The name of the constructor must be consistent with the class name
- There cannot be any return value type declaration at the declaration of the constructor
- You cannot use return in a constructor to return a value
class Person {
public Person(){ // Declare the constructor method
System.out.println("A new Person object is created.") ;
}
}
public class ConsDemo01 {
public static void main(String args[]) {
System.out.println("Declaring an object: Person per = null ;") ;
Person per = null ;// Declare object without calling constructor method
System.out.println("Instantiating an object: per = new Person() ;") ;
per = new Person() ; // Call the constructor method when instantiating the object.
}
}
operation result:
Constructor/Method
- The constructor is called implicitly .
Each time a new object instance is created, the constructor method is forced to be executed once
- Constructors can also be called explicitly by the programmer
Call the constructor of the parent class in the subclass
- The construction method will have:
Default constructor : A constructor without parameters. If the programmer does not provide any construction method, the compiler automatically provides a construction method ; as long as the programmer provides a construction method, the system no longer provides a default construction method.
The default construction method provided by the compiler only does one thing: Call the default constructor of the parent class
New syntax
Java:
PlayingCard cardSeven = new PlayingCard(); // Java
C++:
PlayingCard *cardEight = new PlayingCard; // C++
final keyword
- Depending on the program context, the Java keyword final has the meaning of " cannot be changed " or "final state"
- It can modify non-abstract classes , non-abstract class member methods and variables
- Final classes cannot be inherited and have no subclasses. Methods in final classes are final by default.
- Final methods cannot be overridden by subclass methods, but they can be inherited
- Final member variables represent constants and can only be assigned once. The value will not change after assignment.
- final cannot be used to modify constructors .
final class
- When designing a class, if the class does not need to have subclasses, the implementation details of the class are not allowed to change, and you are sure that the class will not be extended, then design it as a final class.
- This kind of class is usually called the perfect class
final method
- If a class does not allow its subclasses to override a method, it can declare the method as final.
- There are two reasons for using final methods:
- Lock the method to prevent any inheriting class from modifying its meaning and implementation.
- Efficient. The compiler will switch to the inline mechanism when it encounters a final method call , which greatly improves execution efficiency.
final variable (constant)
- Member variables modified with final represent constants. Once the value is given, it cannot be changed.
- There are three types of variables modified by final: static variables, instance variables and local variables , which represent three types of constants respectively.
- Once a final variable is given an initial value, the value cannot be changed.
static final int i2 = 99;
- When a final variable is defined, it can be declared first without giving an initial value . This type of variable is also called a blank final . No matter what the situation, the compiler ensures that the blank final must be initialized before use . However, blank final provides greater flexibility in the use of the final keyword final. For this reason, the final data members in a class can be implemented differently depending on the object, but maintain their constant characteristics .
class BlankFinal {
final int i = 0; // Initialized final
final int j; // Blank final
// Blank finals MUST be initialized // in the constructor:
BlankFinal() {
j = 1; // Initialize blank final
p = new Poppet();
}
BlankFinal(int x) {
j = x; // Initialize blank final
p = new Poppet();
}
public static void main(String[] args) {
BlankFinal bf = new BlankFinal();
}
}

final only asserts that the relevant variable will not be assigned a new value and does not prevent the variable value from being changed within the object. Such as a response to a message.
class Box {
public void setValue (int v);
public int getValue () { return v; }
private int v = 0;
}
final Box aBox = new Box(); // can be assigned only once
aBox.setValue(8); // but can change
aBox.setValue(12); // as often as you like
END