How to design classes in Java for beginners
After learning java for the first time, we will find that the difficulty of Java is not that Java syntax is difficult to learn, but that we are hung on the “rope” of how to design classes. This is exactly one of the gaps between Xiaobai and programmers who have been employed for many years. So let’s share my opinion today:
So how to design classes? Is there any principle to follow? The answer is as follows!
Interviewer: “please use C++/java/Python and other languages to design a calculator running on the console in an object-oriented way.”
The interviewer buried his head for 10 minutes and wrote the program to realize the calculator function. Here, the program will not go up. But Birdie’s program is probably like this: a class, a main method and a series of code, there is a class and a main method from the beginning to the end. But this is not conducive to the later operation and maintenance, and the scalability is very poor.
Therefore, it is very important to design and implement functional subpackage by “class”. The design idea is as follows:
The basic functions of calculator are + – * /. You can write a class for addition, subtraction, multiplication and division, and inherit the operation class (parent class). So how to give users a good method of operation? Then you have to design a class (operationcompany class). This class is very special. It is mainly responsible for the calculation of user input and new object. What do you mean? For example, if the user wants to implement the multiplication operation, then after the user enters the multiplication sign *, the method of this class will take the multiplication class as the template, and a new multiplication class object will come out, so as to call the multiplication class method. This model is called the simple factory principle.
Among them, the separate design of addition, subtraction, multiplication and division embodies the encapsulation feature, while the subclass (addition, subtraction, multiplication and division) of operation (parent) reflects the polymorphism of subclass. It is the common saying that “one dragon has nine children, and each of them is different”, which is exactly the reason; while the child class inherits the parent class operation class, which is where the inheritance is located. So in the process of programming, only when we think about the product can we get high-quality code lines at our fingertips.