The article directories

  • Class and object exercises
    • Practice a
    • Exercise 2
  • Finished!

Class and object exercises

\

Practice a

\

Write a Calculator class with two attributes num1,num2.

The values of these two data cannot be initialized at the same time as they are defined. Finally, four operations of addition, subtraction, multiplication and division are implemented.

Code implementation:



\

Compiler implementation effect:

\

\

Note:

First of all, we implemented the internal member variables of the Calculator class. We modified them with private, encapsulated them with getter and setter methods, and realized the function of addition, subtraction, multiplication and division. In short, we realized the encapsulation function of the class. Handy for callers of classes.

\

Exercise 2

\

Implement swapping the values of two variables. Requirement: The values of the arguments need to be swapped.

\

Method one:

\



Compiler implementation effect:

\

\

Note:

In the code of method one, we use public to decorate the member variables in myValue class, and do not use the form of encapsulation, so later in the main method, we access the member variables through the object of new, so as to exchange the arguments.

\

Method 2:

\



\

Compiler implementation effect:

\

\

Note:

In the method 2 code, the member variables in myValue class are private and encapsulated, so in the main method, we assign values to the arguments through the encapsulated getters and setters. The swap method is used to swap arguments.

\

Ok, today’s exercise is shared here, I hope you pay more attention to practice. Thank you for your appreciation and attention!!


\

Thank you!!


\

Finished!