Java Class and Object with First Program

<< Previous Chapter Next Chapter >>
  • Classes & Objects in Java:

    What is an object?
    Objects and classes are the base of object oriented programming. It is difficult to understand the OOPs concept without understanding class and object.
    an Object is the executable copy of the class, its another name is instance. There can be any number of objects for a given class in the memory. In real world an object is an entity, for example our home, our bike, car, fan or anything which has a physical existence even me and you.

    There are 2 characteristics of object:
    1. Property or state -       e.g. a car has color, wheels, companyName, head light etc.
    2. Behavior          -           e.g. a car runs, blow horn, flash light, apply break etc.

    Both of the above (property & behavior) are bundled in a single unit which is referred as object. In programming term we call the property as a data member (or fields) and behavior as methods.


    Benefits or advantages of using Object:
    1. Modularity – the source code of object can be written independently of the code of other objects.
    2. Data security or data hiding – we always make the methods accessible to the outside world but the data or property is always private to the object or class, no one can access the data directly, instead the methods access it and act as an interface for outsiders.
    3. Reusability – if object is already created by one person in a team then no need to create it again, we can directly reuse it.
    4. Easy code debugging – in case of any issues with an object just plug in another object as a replacement instead of chaining complete program. For a real example if wheel burst in a car just change its tube instead of replacing the car.

    What is a class?

    A class is a logical representation of a physical object. It is a structure that defines the data and the methods to operate on that. When we write a program in java language, all program data is wrapped in a class. For example I will say a Car is a logical representation which means, Car is a class whereas Honda Accord car or Range Rover is having physical existence which means it is an object. Another example is that the Bird is a class and hen or parrot is an object.

    In another word we can say a class is a blueprint from which individual object is created.

    Without class we cannot write even a very simple program because java is a pure object oriented programming language.

    Let’s take a very simple “Hello World” example in java, then we will create little big program.
    Create a file with name HelloWorldExample.java in any folder and paste below code in it:
    I am keeping this file at E:\testjava\HelloWorldExample.java

    public class HelloWorldExample {

           public static void main(String[] args) {

                  System.out.println("Hello World!");
                 
           }

    }

    In above simple program we are using System.out.println() method to print a message on console, there is a popular interview question that what is the System, out and println in above statement. So, we will discuss it in detail in this chapter itself.

    Install, configure and run program in java
    Now, let’s try to install java, configure it and run above program. Download latest version of java from downloads section of www.oracle.com, once it is downloaded, install it. It’s very simple to install. After installation we need to configure java home and path environment variable.

    To set the path, please follow steps below:

    1.  Right click on My Computer (or in Computer in windows 7), then right click on Advanced System Settings.


       
    2. Click on Environment Variables button, create a new variable inside System Variables section and name it as JAVA_HOME and enter the home location of java where it is installed, for example in my system I have installed java at C:\Program Files\Java\jdk1.8.0_25



    3. Now, select the path system variable, put semicolon and add the path till bin folder like C:\Program Files\Java\jdk1.8.0_25\bin


    4. Now, let’s test whether it is configured properly or not, open command prompt and enter command javac and java one by one and press enter, if command is recognized and some result is coming then we are sure that we have configured it properly:



    We are done now. Let’s try to run the simple program. We have 2 ways to execute it
    1. Through command prompt
    2. Through IDE (e.g. eclipse, netbeans etc.) – I will be using eclipse in this tutorial.

    Run Java program through command prompt:
    Open command prompt and change directory to E:\testjava. Then enter
    javac HelloWorldExample.java, this command will compile our java file, and generate .class  file in same folder.

    Once it is compiled, enter following command to run the program, this command will execute our program and display output “Hello World!
    java HelloWorldExample



    Run Java program through Eclipse IDE:
    Second way to execute java program is through an IDE. First download and install the eclipse IDE from https://eclipse.org/downloads/ site. I am using eclipse KEPLER (version) in this tutorial.

    1. Open eclipse IDE, it will first ask to select a workspace. Workspace is the folder where we are going to create our all projects / programs. Enter E:\JavaWorkSpace or anywhere you want, it will take some time to open.

    2. Once eclipse is opened, close the welcome window if it appears and Go to File –> New –> Project. Select Java Project and click next.



    3. Enter project name javaSampleProjects and click next (no need to fill any other data as of now, we will discuss the eclipse IDE in a separate chapter).


    Click finish; say yes if any message box appears.

    4. Now, the project explorer window will appear, right click on src -> New -> Class, enter class name HelloWorldExample and click finish. Now, open the file and paste our HelloWorld code inside.





    5. Now, Right click on file or inside the code and click Run As -> Java Application. Output will be displayed as follows on console screen (If console widow is not appearing on bottom click on Window -> Show View -> Console or press Alt+Shift+Q, C):



    Following is another example with few more functionalities; this example defines a class Bird with some properties and methods and creates some real objects of it.

    Create a java file with name Car.java:

           public class Car {

               // 3 private data members or fields of Bird class
               private String color;
               private String companyName;
               private String NoOfGears;

               /*Set of methods or behavior of this class */
                  public void run() {
                         System.out.println("Car is running..");
                  }

                  /*Below set of methods acts as an interface between private members of this class and other outside classes
                   these methods are declared so that out other classes can access private members of this class. */
                  public String getColor() {
                         return color;
                  }

                  public void setColor(String color) {
                         this.color = color;
                  }

                  public String getCompanyName() {
                         return companyName;
                  }

                  public void setCompanyName(String companyName) {
                         this.companyName = companyName;
                  }

                  public String getNoOfGears() {
                         return NoOfGears;
                  }

                  public void setNoOfGears(String noOfGears) {
                         NoOfGears = noOfGears;
                  }   

           }

    Create another java file with name CarImpl.java: (Car Implementation)
    Now, in below program we are trying to create few objects of above class:

    public class CarImpl {

           public static void main(String args[])
           {
                  //creating object of car class
                  Car hondaAccord = new Car();
                  //setting car properties
                  hondaAccord.setName("Honda Accord");
                  hondaAccord.setColor("Blue");
                  hondaAccord.setCompanyName("Honda");
                  hondaAccord.setNoOfGears("5");
                 
                  System.out.println("Car Name: " + hondaAccord.getName());
                  System.out.println("Color: " + hondaAccord.getColor());
                  System.out.println("Company: " + hondaAccord.getCompanyName());
                  System.out.println("No Of Gears: " + hondaAccord.getNoOfGears());
                  hondaAccord.run();
                 
                  //creating object of car class
                  Car rangeRover = new Car();
                  //setting car properties
                  rangeRover.setName("Range Rover");
                  rangeRover.setColor("White");
                  rangeRover.setCompanyName("TATA Motors");
                  rangeRover.setNoOfGears("6");
                 
                  System.out.println("\nCar Name: " + rangeRover.getName());
                  System.out.println("Color: " + rangeRover.getColor());
                  System.out.println("Company: " + rangeRover.getCompanyName());
                  System.out.println("No Of Gears: " + rangeRover.getNoOfGears());
                  rangeRover.run();
                 
           }
          
    } 
    Output:


    << Previous Chapter Next Chapter >>




No comments:

Post a Comment