[4] Java classes and objects

Keywords: Java R Language IntelliJ IDEA

Java classes and objects


The main unit of object-oriented programming language is class, and class is a user-defined type. The variables created by class are called objects. Classes and objects are the most common words in object-oriented programming.

Three foundations of object orientation:

  • Encapsulation, packaging data types and methods
  • Inheritance. The new class uses the features of the old class. Java does not support multiple inheritance
  • Polymorphism, different effects that occur when objects of different classes use methods with the same name

Preliminary understanding of Java classes

In C language, a custom type is a structure. Many basic data types can be encapsulated in the structure. Then the variables created with the structure have these basic data types at the same time.

In C + +, custom types are classes and structures. C + + adds the concept of class on the basis of C language, and changes the structure (there can be member functions in the structure, which is not allowed in C language).

In Java, a custom type is a class. The concept of structure has been removed and the position of structure has been directly replaced by class.

Look directly at the example:

Correct usage of structure in C language:

#include<stdio.h>

struct MM
{
  char name[10];
  int age;
};

int main()
{
    struct MM mm={"Alice",19};
    return 0;
}

The structure of C language can only encapsulate data types without member functions, and C language structure cannot be initialized in the structure.

Structure of C + +

#include<iostream>
using namespace std;

struct MM
{
  string name="Coco";
  int age=20;
  void print()
  {
      cout<<name<<'\t'<<age<<endl;
  }
};

int main()
{
    MM mm;
    return 0;
}

A C + + structure is a member function that can exist in the structure (it can be implemented in the structure or outside the structure). Then, the data members of the structure of C + + can be initialized in the structure or outside the structure, or a member function can be used to initialize the data members of the structure. Then the structure of C + + can be created without the struct keyword.

C + + classes:

#include<iostream>
using namespace std;

class MM
{
    public:
    MM(string name,int age):name(name),age(age){}
    protected:
    string name;
    int age;
};

int main()
{
    MM mm("Alice",20);
    return 0;
}

The class of C + + is actually the same as the structure, except that the default permission qualifier is different.

When it comes to Java, in order not to be as complex as C + +, the concept of structure is directly removed, and then classes are directly used as custom types of Java language.

class MM{
    String name;
    int age=19;
    public MM(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public void print()
    {
        System.out.println(name+"\t"+age);
    }
}

public class Demo{
    public static void main(String[] args){
        MM mm=new MM("Alice",19);
        mm.print();
    }
}

Features of Java classes:

  • Java classes are also represented by the class keyword
  • When encapsulating Java classes, there is no need to write semicolons at the end, while C language and C + + need to write semicolons.
  • Java does not have the concept of initializing parameter list, but C + + does
  • When you need to use Java permission qualifiers, you need to write them once at a time, while C + + needs to write them once many times.
  • When encapsulating a class, the data members in the class are not initialized, the number type is initialized to 0 by default, and the string is initialized to null
  • Generally, data members in a class are called attributes, and member methods in a class are called behaviors

Preliminary understanding of Java objects

If you don't understand the concept of object in your first reaction, you are half successful. In fact, the so-called object is the variable instantiated by the class. It's like building a robot. Before making a robot, package all parts, and then use these packaged parts to realize some functions. This is the process of packaging classes. Then these packaged parts are processed slightly to create robot 1, and then robot 1 is the object of this class. Object oriented programming is to transform the robot and add what it needs.

Simply encapsulate a Java class, then create class objects, and finally simply implement some functions:

class MM{
        String name="Alice";
        int age=20;
        public void initData(String name1,int age1){
                name=name1;
                age=age1;
        }
        public void print(){
                System.out.println(name+"Information about:"+"full name:"+name+"\t Age:"+age);
        }
}

public class Demo {
        public static void main(String[] args) {
                MM mm=new MM();
                mm.print();
                mm.initData("Coco",19);
                mm.print();
        }
}

Output results:

Alice Information: Name: Alice	Age: 20
Coco Information: Name: Coco	Age: 19

The function of the above program is to encapsulate a beauty class, and then the beauty information has name and age. The function (method) of this beauty class is initialization and printing. In the main method, the object mm of MM class is created, but this mm is a reference. It exists in the stack area and cannot be used directly. It can only be used by applying for a piece of memory in the heap area. The function of the main method is to create an object, print a default, initialize new information, and then print the information of the object.

Java construction method

Characteristics of construction method:

  • The method name is the same as the class name
  • no return value
  • Mainly used to initialize class objects
  • When creating an object, the constructor will be called first
  • When the constructor is not written manually, there will be a default parameterless constructor in the class
  • If the constructor is written manually, the default constructor does not exist
  • Construction methods can also be overloaded
  • In Java, whether public and other permission qualifiers are written before the constructor has little effect
class MM{
    String name;
    int age;
    MM(String name1,int age1){
        name=name1;
        age=age1;
        System.out.println("Call constructor");
    }
    public void print()
    {
        System.out.println(name+"\t"+age);
    }
}

public class Demo{
    public static void main(String[] args){
        //MM mm=new MM(); 	 An error will be reported, because the constructor with parameters is written manually, and the default does not exist
        MM mm =new MM("Alice",20);	//Print: call constructor
        mm.print();		//Will print: Alice 		 twenty
    }
}

Output results:

Call constructor
Alice	20

Because Java has the mechanism of automatic garbage collection, Java has no concept of destructor, and C + + has no mechanism of automatic garbage collection, so c + + has the concept of destructor.

this keyword in Java

  • Represents the current object
  • It is mainly used to distinguish parameters with the same name
  • The constructors of this() mode should be written in the first line of the constructors

It is similar to the this keyword in C + +. This in C + + and Java represents the current object and is mainly used to identify parameters with the same name. The difference is that this in C + + is a pointer and this in Java is a reference.

Look directly at the code to find the difference:

this in C + +:

class MM
{    
public:    
	MM(string name,int age)    
	{        
		this->name=name;        
		this->age=age;    
	}    
protected:    
	string name;    
	int age;
};

this in Java:

class MM{    
	String name;    
	int age;    
	MM(String name,int age){    	
		this.name=name;        
		this.age=age;    
	}
}

In Java, how an object accesses a member in a class, this accesses it, because this means the current object.

class GG{        
	String name;        
	int age;        
	GG(String name,int age){                
		this.name=name;                
		this.age=age;        
	}        
	public void print(){                
		System.out.println(this.name+"\t"+this.age);        
	}        
	public void Fun(){                
		System.out.println(name+"The information is as follows:");                
		this.print();        
	}
}

public class Demo02 {        
	public static void main(String[] args) {               
		GG gg=new GG("Cukor",21);               
		gg.Fun();               
		GG gg2=new GG("Jack",20);               
		gg2.Fun();        
	}
}

Print results:

Cukor The information is as follows: Cukor	21
Jack The information is as follows: Jack	20

You can see that when gg calls the Fun method, this represents gg, and when gg2 calls the Fun method, this represents gg2.

When there are multiple constructors in the class, you can call each other in the form of this(), but this statement should be placed on the first line of the constructors. This operation is a bit like the C + + delegate construction, but the C + + delegate construction should be written in the initialization parameter list

class Test{        
	int iNum;        
	double dNum;        
	char cNum;        
	Test(){                
		System.out.println("Nonparametric construction method");        
	}        
	Test(int iNum){                
		this();                
		this.iNum=iNum;                
		System.out.println("A parameter construction method");        
	}        
	Test(int iNum,double dNum){                
		this(iNum);                
		this.dNum=dNum;                
		System.out.println("Two parameter construction method");        
	}        
	Test(int iNum,double dNum,char cNum){                
		this(iNum,dNum);                
		this.cNum=cNum;                
		System.out.println("Three parameter construction method");        
	}
}

public class Demo03 {        
	public static void main(String[] args){                
		Test ts1=new Test();                
		System.out.println("========================================");                
		Test ts2=new Test(666);                
		System.out.println("========================================");                
		Test ts3=new Test(888,3.14);                
		System.out.println("========================================");                
		Test ts4=new Test(888,3.14,'A');        
	}
}

Output results:

Nonparametric construction method
========================================
Nonparametric construction method
 A parameter construction method
========================================
Nonparametric construction method
 A parameter construction method
 Two parameter construction method
========================================
Nonparametric construction method
 A parameter construction method
 Two parameter construction method
 Three parameter construction method

this(); In this way, the of this () series must be placed on the first line of the construction method!!!

Cukor Chuk home page

Posted by tomjung09 on Mon, 20 Sep 2021 04:53:02 -0700