Java Class and Object Example

by Didin J. on Dec 09, 2016 Java Class and Object Example

Java class and object example in best practice using full source code with Netbeans 8.2 IDE

One of the essential features of java programming is Object because java is pure object oriented programming. Classes are blueprint or prototype of an object. Here's I want to show you what is Java class and object example.

Next, create a project using Netbeans 8.2 and Java 8 will be an easy way, name this new project with JavaClassExample and leave all properties to default. After project generated, there will be a package name javaclassexample with main java class named JavaClassExample.

Create new java class by right clicking on the package the select New -> Java Class then name it Next type or put this code into this new java class.

package javaclassexample;

public class Product {
    String name = "LED Monitor";
    double price = 2000000;
    int quantity = 10;
    void changeName(String newName) {
        name = newName;
    void changePrice(double newPrice) {
        price = newPrice;
    void changeQuantity(int newQuantity) {
        quantity = newQuantity;
    void printChanges() {
        System.out.println("Product: "+name+", Price: "+price+", Quantity: "+quantity);

Here's we create an object Product with representing by Product class which has fields String name, double price, and int quantity. It also has methods for its fields, there is changeName, changePrice, changQuantity with its own parameter and one method to print fields changes to the console.

As you see there's a different data type in fields section which String is an object of text, double and int is primitive java types that represent numerically. And here's how to instantiate(call) an object and its method. Put this code into the body of the main java class.

package javaclassexample;

public class JavaClassExample {

    public static void main(String[] args) {
        // Create 2 product object
        Product product1 = new Product();
        Product product2 = new Product();
        // Invoke method on each objects

In above code that shows 2 objects is created, there is product1 and product2. After object created each of those objects call its methods and put/set new parameter inside that methods. So, when we run this application, those object print new fields values by method printChanges(). And the results like this:

Product: Keyboard, Price: 85000.0, Quantity: 100
Product: Mouse, Price: 55000.0, Quantity: 120
BUILD SUCCESSFUL (total time: 1 second)

That it's a simple class and object example for today.