See the following example which uses 2 classes, one contains only the main method while the other contains the instance variables and methods we want to use through our objects.
The 1st class is:
Note that the 1st class contains 2 instance variables and 3 methods of type void, remember that a void function returns nothing to its calling statement.
Method set is responsible for assigning values to the variables of the object created from class Program by getting those values from the calling statement through the method parameter list.
Remember that a private instance variable (or data member) cannot be used by any other class declared outside its class, but the method set is a member of the same class. So it can manipulate with these variables.
Method sum is responsible for summing the values of the 2 variables and printing the summation. here we have a casting, where casting is important while we are using different datatypes, Java cannot make automatic casting as in c++, so it is very important to put (double) before (x+y) because the result is to be stored inside a double declared variable.
Casting is usually done to avoid data loss.
Casting is usually done to avoid data loss.
We have also a new method for printing, it is println which is responsible for printing what is written in the parameter list, then making a new line automatically.
The third method is responsible for printing the values of x & y.
In the 2nd class we have the main method which contains the declaration of 2 objects from the 1st class P0, P1, and calling the methods inside the 1st class throughout its objects.
Note that we didn't assigned values for the variables inside object P1 which means that they are zeroes by default.
Note that we didn't assigned values for the variables inside object P1 which means that they are zeroes by default.
سامر المناصرة
ليست هناك تعليقات:
إرسال تعليق