This lesson will be the core of all past lessons, this gonna be the major component of java, by this lecture's you'll learn about classes and objects, as we all know that classes define custom data types of an object. Let's check out the program below which defines a new "Rectangle" class
The class Rectangle declares two integer fields "width" and "height".
then in the main method, we create a new Rectangle Object with new Rectangle() and assign it to variable "rect" and we set the rectangle's width field to 100 and print the value of the field. Guess what the program prints? The value of the "width" field of our newly created Rectangle object is 100. Now we set the value of the "height" field of the Rectangle object to 200 and then print the value of the field. You should see now the print result of 100,200 for the width and height. now we create another rectangle object and call it "rect2" and then set the width to 20 and height to 40 and then print both fields. now you should see 100,200, 20,40 in the following order. we declare again a new class point with integer fields x and y see the above codes for reference. and then we create a new Point object in the main method and initialize a value of "x" to 6 and "y" to 10, then we assign it to variable "p". it also possible to use a class as a data type for a field of another class. Add a field "position" to class "Rectangle" with type "Point" in the main method we assign variable "p" to the "position" field of "rect2" finally we point "rect2.position.x" and "rect2.position.y" now run it with your compiler and see what it prints.
The class Rectangle declares two integer fields "width" and "height".
then in the main method, we create a new Rectangle Object with new Rectangle() and assign it to variable "rect" and we set the rectangle's width field to 100 and print the value of the field. Guess what the program prints? The value of the "width" field of our newly created Rectangle object is 100. Now we set the value of the "height" field of the Rectangle object to 200 and then print the value of the field. You should see now the print result of 100,200 for the width and height. now we create another rectangle object and call it "rect2" and then set the width to 20 and height to 40 and then print both fields. now you should see 100,200, 20,40 in the following order. we declare again a new class point with integer fields x and y see the above codes for reference. and then we create a new Point object in the main method and initialize a value of "x" to 6 and "y" to 10, then we assign it to variable "p". it also possible to use a class as a data type for a field of another class. Add a field "position" to class "Rectangle" with type "Point" in the main method we assign variable "p" to the "position" field of "rect2" finally we point "rect2.position.x" and "rect2.position.y" now run it with your compiler and see what it prints.
0 Comments