Java Classes and Objects
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Classes and Objects

Jeevadharshan

Java Classes and Objects 

Java is a fully object-oriented programming (OOP) language, meaning programs are built using classes and objects that encapsulate data and behavior together. This approach mirrors real-world entities—for example, a Car object has attributes like color and speed, and behaviors like drive or brake. 

What is a Java Class? 

A class is a blueprint or template used to create objects. It defines:
  • Attributes (fields): data the object holds 
  • Methods: actions the object can perform

Create a Class in Java 

Use the class keyword to define a class. By convention:
  • Class names start with an uppercase letter 
  • The filename must match the public class name
public class Book { 
   String title = "Java Basics"; 
Here, Book is a class with one attribute title. 

What Is an Object in Java? 

An object is an instance of a class. It represents a specific entity created from the class blueprint. 

Create and Use an Object 

You create an object using the new keyword, then access its fields or methods with the dot (.) operator. 

public class Book { 
    String title = "Java Basics"; 

    public static void main(String[] args) { 
       Book myBook = new Book();   // create object 
 
        System.out.println(myBook.title);  // access attribute 
    } 
}  

Output 

Java Basics

Creating Multiple Objects 

A single class can produce many objects, each representing a different instance. 
 
public class Laptop { 
    String brand = "Dell"; 
 
    public static void main(String[] args) { 
        Laptop laptop1 = new Laptop(); 
        Laptop laptop2 = new Laptop(); 
 
        System.out.println(laptop1.brand); 
        System.out.println(laptop2.brand); 
    } 
}  

Output 

Dell 
Dell 
 
Each object has its own memory allocation, even if values are the same.

Using Multiple Classes in Java  

In real projects, classes are usually separated across files for better organization. One class defines data and behavior, while another contains the main() method to run the program. 
 
File: Student.java 
public class Student { 
    String name = "Anita"; 
    int marks = 85; 
File: SchoolApp.java 
public class SchoolApp { 
    public static void main(String[] args) { 
        Student s = new Student(); 
        System.out.println(s.name + " scored " + s.marks); 
    } 
}

Output 

Anita scored 85 

Compile and Run Multiple Classes 

When classes are in separate files but the same folder: 

javac Student.java 
javac SchoolApp.java 
java SchoolApp
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !