Classes Objects Java


Classes Objects Java tutorial explains creation of objects, writing classes, methods, variables etc. for a Beginner

Java Classes

To write the code in Java, a class is required. It is the basic construct for a Java program. Following denotes class by name Demo.

public class Demo
{
  // some code
}

The name of the class is Demo. It is declared public and means any other class can access the class Demo and make use of its code without any permission. "public" is known as access specifier. "static" is known as access modifier.

Java permits to write any amount code (may be hundreds of lines) within class declaration. Braces indicates the class boundaries. Write any code within 2 and 5 lines. Writing outside the braces is a compilation error.

Now let us learn how to place some code.

public class Demo
{
  public static void main(String args[])
  {
    System.out.println("Hello World");
  }
}

We placed the main() method in the class Demo. main() is very big one in Java compared to C/C++. But every word has got a meaning to compiler. It is clearly discussed in "public static void main(String args[])".

How to compile and run the above code is discussed in "Basic Class Structure, Compilation and Execution".

Now let us place our own method (main() is predefined method) and a variable in the class.

public class Demo
{
  int marks = 50;
  public void display()
  {
    System.out.println("Hello 1");
  }
  public static void main(String args[])
  {
    System.out.println("Hello World");
  }
}

display() is our own method and variable is marks assigned with 50. Now how to call them from main() method.

Java Objects

To call marks variable and display() method, we require an object of Demo class. Without object, it is not possible to call them because Java is an object-oriented language.

Classes Objects Java: Let us create an object of Demo and call the method and variable.
public class Demo
{
  int marks = 50;
  public void display()
  {
    System.out.println("Hello 1");
  }
  public static void main(String args[])
  {
    System.out.println("Hello World");
    Demo d1 = new Demo();
    System.out.println(d1.marks);
    d1.display();
  }
}

Observe the code.

Demo d1 = new Demo();
System.out.println(d1.marks);
d1.display();

d1 is known as object of Demo. Syntax is using class name two times in the statement and new is keyword of Java. Using d1 we can call the variable as d1.x and method d1.display();

There are discussed more clearly in "Using Local and Instance Variables" and "Using Methods and Method Overloading".

For more clarification, read the following.

1. What is a class in Java?
2. Classes of Java

Leave a Comment

Your email address will not be published.