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.
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
}
}
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);
}
}
final
, if the object is changed, the compiler will throw an error.As we mentioned in [Day 12: Arguments and Parameters] (https://ithelp.ithome.com.tw/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);
}