Page 354 - CITS - Computer Software Application -TT
P. 354

COMPUTER SOFTWARE APPLICATION - CITS



           LESSON 94 - 100: JAVA Classes, Overloading and

                                          Inheritance


            Java Classes/Objects


           Classes and objects are the two main aspects of object-oriented programming.
           Java is an object-oriented programming language.
           Everything in Java is associated with classes and objects, along with its attributes and methods. For example:
           in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and
           brake.
           A Class is like an object constructor, or a “blueprint” for creating objects
           Create a Class

           To create a class, use the keyword class:
           Main.java
           Create a class named “Main” with a variable x:
           public class Main {
             int x = 5;
           }

           Create an Object
           In Java, an object is created from a class. We have already created the class named Main, so now we can use
           this to create objects.

           To create an object of Main, specify the class name, followed by the object name, and use the keyword new:
           Example
           Create an object called “myObj” and print the value of x:
           public class Main {

             int x = 5;
            public static void main(String[] args) {
              Main myObj = new Main();
              System.out.println(myObj.x);
             }

             }
           Java Methods
           A method is a block of code which only runs when it is called.
           You can pass data, known as parameters, into a method.
           Methods are used to perform certain actions, and they are also known as functions.

           Why use methods? To reuse code: define the code once, and use it many times.
           Create a Method
           A method must be declared within a class. It is defined with the name of the method, followed by parentheses
           (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own
           methods to perform certain actions:






                                                           341
   349   350   351   352   353   354   355   356   357   358   359