In this topic, we will learn classes in Java. A class is the kind of an entity in real world. Each class has certain attributes . For example – Car, Student, Person, Phone, Account. All of these are classes. Each class has unique attributes (also called as members – fields/methods in Java). At broad level, there are 2 types of classes.
  • Concrete classes – all methods are defined. We can create objects of concrete classes. When we create a object of the class, default constructor is called. We can also create parameterized constructors.
  • Abstract classes- In abstract class, at least one method is not defined. (just declared). We can not create objects of Abstract classes.
Constructors are special methods in class with the same name as that of a class. These methods get called automatically when we create an object of the class. Here is an example of Concrete class.

package oops;

/**
 * Created by Sagar on 16-04-2016.
 */
public class Classes {

    public static void main(String [] args){
        //Below statement creates the object
        Car audi = new Car();

        //accessing the method of the class Car
        audi.setMake("Audi");
        audi.setYear(2011);
        System.out.println("Audi is the Object of type Car");

        //accessing the field of the class Car
        System.out.println("Year of audi car object -> " + audi.year);

        //Another car object - Huyndai Santro
        Car i30 = new Car("Huyndai",2001);
        System.out.println("Year of i30 -> " + i30.year);
    }
}

class Car{
    //Each class has one or more Members (Fields and Methods)

    //Fields of Class Car
    int year;
    String make;
    String model;

    //Constructors of Class
    //There can be one or more constructors
    //If you do not declare any constructor,
    //default empty constructor is used.
    Car(){
        System.out.println("Constructing empty object");
    }

    Car(String make, int year){
        System.out.println("Constructing Car with parameters");
        this.make = make;
        this.year = year;
    }

    //Methods of class
    public void setMake(String make){
        this.make = make;
    }

    public void setModel(String model){
        this.model = model;
    }

    public void setYear(int year){
        this.year = year;
    }
}
Here is the output of above example.

Constructing empty object
Audi is the Object of type Car
Year of audi car object -> 2011
Constructing Car with parameters
Year of i30 -> 2001

Web development and Automation testing

solutions delivered!!