Classes and Objects in Java Programming – Code Example

In this post we will learn (java syntax) what are classes and objects in Java programming. Classes and objects are fundamental object oriented programming concepts. In previous post we discussed some important object oriented programming concepts. If you want to learn about classes and objects, class constructor method, constructor parameters, instance variables, class methods and main method then read this post.

In this simple program we will learn how to create a class and class objects in Java programming. Further we will also learn how to create instance variables (attributes) and methods for class in Java programming.

[js]

package carclassjava;

// following is the syntax to create a public class named as CarClassJava
public class CarClassJava {
int modelYear; // this is how we create an instance variable (attribute) in class

// following is the constructor method for class
public CarClassJava(int year){
modelYear = year;
}

// following is the method of this class
public void startEngine(){
System.out.println("Car is started");
}

// following is the method of this class
public void getModelYear(){
System.out.printf("Car’s Model is: %dn", modelYear);
}

// following is the main method of this class. Every java program needs a main method
public static void main(String[] args) {
// Following is the syntax to create an object of class
CarClassJava myCar = new CarClassJava(2015);
myCar.startEngine(); // we called class method startEngine over the object myCar
myCar.getModelYear(); // we called class method getModelYear over the object myCar
}

}

[/js]

Output:

classes and objects in java

6 thoughts on “Classes and Objects in Java Programming – Code Example

  1. 14. System.out.println(“Car is started”);
    Can We do According to the Following Method
    System.out.println(“Model YEar OF Car = 2015”)
    ANd in line 14 Can we Remove (ln)……………………??????????????

  2. Below the line no. 14
    SiR Can We add (System.out.println(“Model oF Car IS = 2015”); to show the CAR’S MoDeL……???

    1. yes, you can do like this:

      System.out.printf(“Model of the car is %d\n”, modelYear);

      please note that I have used printf instead of println

  3. Sir PLEASE TELL us THAt foR BSSE 2nd SEMESTER ..
    WE CLick at programing then click at java
    all of the related topics are uploaded here for us BSSE 2nd semester

Leave a Comment

Your email address will not be published. Required fields are marked *