JAVA TUTORIAL

Java Intro Java Features Java vs C++ Java Simple Program Java Applet vs Application JVM,JDK or JRE Java Keywords Java Variables Java Literals Java Separators Java Datatypes Java Operators Java Statements Java Array Java String

CONTROL STATEMENTS

Java If-else Java While Loop Java Do-While Loop Java For Loop Java For-each Loop Java Switch Java Break/Continue

JAVA METHODS

Java Method Java Overloading Java Overriding

JAVA CLASSES

Java OOPs Java Classes/Objects Java Inheritance Java Polymorphism Java Encapsulation Java Abstraction Java Modifiers Java Constructors Java Interface Java static keyword Java this keyword

Java Classes and Objects

Java Class

In Java everything is encapsulated under classes. Class is the core of Java language. It can be defined as a template that describe the behaviors and states of a particular entity.

In Java, class is declare using class keyword. A class contain both data member and methods that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods.

Thus, the instance variables and methods are known as class members.

Create a class in Java

We can create a class in Java using the class keyword.

Syntax:

class ClassName {
    // dataMember
    // methods
}

Example:

class Simple {
    // dataMember
    int number = 3;

    // method
    void message()
    {
        System.out.println("Hi i'm method in a class Simple")
    }
}

In the above example, we have created a class named Simple. It contains a dataMember number and a method named message().

Java Objects

Object is an instance of a class. An object in OOPS is nothing but a self-contained component which consists of methods and properties to make a particular type of data useful. When you send a message to an object, you are asking the object to invoke or execute one of its methods as defined in the class.

In a simple word object is a real world entity which have predefined attributes and its beheviour. It has a physical thing as well as abstract in nature.

Creating an Object in Java

Here is how we can create an object of a class.

Syntax:

ClassName ReferenceVariable = new ClassName();

Example:

class Simple {
    int x = 10;

    public static void main(String[] args) {
        Simple obj = new Simple();
        System.out.println(obj.x);
    }
}

Output:

10

Multiple Objects

We can also create multiple objects of one class. Here is the example of multiple object creation.

class Simple {
    int x = 10;
    int y = 20;

    public static void main(String[] args) {
        Simple obj1 = new Simple();
        Simple obj2 = new Simple();
        System.out.println(obj1.x);
        System.out.println(obj2.y);
    }
}

Output:

10
20