bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Classes
Java•Java Classes

Java Classes and Objects

Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes , such as weight and color, and methods , such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class .

In this example, we create a class named " Main " with a variable x :

public class Main {
 int x = 5;
}

Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.

Create an Object

In Java, an object is created from a class. After defining a class, you can create objects from it using the new keyword:

myObj

Multiple Objects

You can create multiple objects of one class:

Main

Using Multiple Classes

You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)).

Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory/folder:

  • Main.java
  • Second.java
public class Main {
 int x = 5;
}
class Second {
 public static void main(String[] args) {
 Main
 myObj = new Main();
 System.out.println(myObj.x);
 }
}

When both files have been compiled

C:\Users\
Your Name
>javac Main.java
C:\Users\
Your Name
>javac Second.java

Run the Second.java file:

C:\Users\
Your Name
>java Second

And the output will be

5

You will learn much more about classes and objects in the next chapters.

Previous

Java OOP

Next

Java Class Attributes

This chapter

Overview
21

Lessons

51m

Read time

1. Java OOP2. Java Classes and Objects3. Java Class Attributes4. Java Class Methods5. Java Constructors6. Java this7. Java Modifiers8. Java Non-Access Modifiers9. Java Encapsulation10. Java Packages11. Java Inheritance12. Java Polymorphism13. Java super14. Java Inner Classes15. Java Abstraction16. Java Interface17. Java Anonymous Class18. Java Enums19. Java Enum Constructor20. Java User Input (Scanner)21. Java Date and Time

On this page

Java Classes/ObjectsCreate a ClassCreate an ObjectMultiple ObjectsUsing Multiple Classes