Day 16 : Object and Class

Chi-Tse Chiang
2022-10-01 19:07:00

Concept

Today, we will introduce basic to advanced object-oriented concepts. The first 15 days of chapters are more about helping us understand the code and apply it. Now that we already know the important basic syntax of Java, we will not go into too much detail on this in the future.

The fundamental concept of object orientation is the relationship between classes and objects. It can be said that a class is a template for an object, and an object is an instance of a class. When we create an object, it inherits all the function variables of its class.

Inheritance actually involves a superclass and a subclass. The subclass inherits all the properties and functions of the superclass and is implemented using the keyword extends. There will be a separate article introducing this concept!

*Category and object demonstration relationship diagram:
We can also think of a mobile phone as an object, its color and appearance as attributes, and the application tools as methods. Finally, the design plan for the phone is like a class.

Object and Class

To create an object in a category, we use new.

/* Create a class name "Main" and a object name "newobj"
   Using "new" this keyword to create object            */
   public class Main{
    String name = "Chi";

	public static void main(String[] args){
	  Main newobj = new Main(); // Class_Name Object_name = new Class_name();
	  System.out.println(newobj.name)      //Output : Jaosn
	}
}

The object inherits the attributes of the class, so we can use the new newobj object to print the string name.

How to create an object: Class_Name Object_name = new Class_name();

If we don't want a property to be changed by an object, we can use the ``final'' modifier.

public class Main{
	final int PI = 3.14159;

	public static void main(String[] args){
		Main math = new Main();
		math.PI = 3.1415926;             //error
		System.out.println(math.PI);
	}
}

After using final, if the object is changed, the compiler will throw an error.

As we mentioned in [Day 12: Arguments and Parameters] (/articles/10299899), we will create two categories, one for storing variables and one for controlling the execution program, and then store them in two files. If you forget, you can go back and review it~

/*First file : Main.java*/

public class Main{
	int grade = 65;
}

/*Second file : Second.java*/

public class Second{
	Main newobj = new Main();
	System.out.println(newobj.grade);
}

We can also use variables in a category by creating objects, even if they are stored in a different file.