- Java Classes
- Java Class Building Blocks
- Defining a Class in Java
- .java Files
- Class With Fields
- Class With Constructor
- Class With Methods
- Class With Nested Class
- Classes and Objects
- Further Concepts for Java Classes
- Lesson: A Closer Look at the «Hello World!» Application
- Source Code Comments
- The HelloWorldApp Class Definition
- The main Method
- Java Class Example
- You may also like
- Calculate Rectangle Perimeter using Java Example
- Swap Numbers Java Example
- Java Factorial Using Recursion Example
- Swap Numbers Without Using Third Variable Java Example
- Calculate Circle Perimeter using Java Example
- Hello World example
- Calculate Rectangle Area using Java Example
- Calculate Circle Area using Java Example
- Find Largest and Smallest Number in an Array Example
- Even Odd Number Example
- Reverse Number using Java
- Java Factorial Example
- 13 Comments
- Cancel reply
Java Classes
Java classes are some of the core building blocks of Java applications, toolkits, frameworks, APIs etc. A small Java application may consist of a single Java class with a main() method in, as covered in the Java main method tutorial. As your Java application grows, keeping all the code in the same class makes it harder and harder to keep an overview of the code. Therefore it might be beneficial to start splitting the Java code up into multiple classes.
A Java class is a single, coherent unit of Java code which belongs together. A Java class may contain a mix of data (variables) and actions (methods). Grouping variables and operations on these variables into Java classes makes it easier to structure your Java program when it gets too big to fit comfortably inside a single Java class. A Java class must be stored in its own file. Therefore, as the class grows, the file you are editing grows too, and becomes harder to keep an overview of in your head.
Your Java application will typically have to contain at least a single Java class, but it may contain as many classes as you see fit to divide your application into. Java also comes with a lot of predefined classes for you, so you don’t have to code every little function you might desire yourself.
Java Class Building Blocks
A Java class can contain the following building blocks:
Fields are variables (data) that are local to the class, or instances (objects) of that class. I will get back to instances later. Fields are covered in more detail in my Java fields tutorial.
Constructors are methods that initialize an instance of the class. Constructors often sets the values of fields in the given instance. Constructors are covered in more detail in my Java constructors tutorial.
Methods are operations that the class or instances of that class can perform. For instance, a method may perform an operation on input parameters, or change the value of fields kept internally in the object etc. Methods are covered in more detail in my Java methods tutorial
Nested classes are Java classes that are defined inside another class. Nested classes are typically intended to either be used only internally be the Java class that contains them, or to be used in connection with the class that contains them. Nested classes are covered in more detail in my Java nested class tutorial.
Not all Java classes have fields, constructors and methods. Sometimes you have classes that only contain fields (data), and sometimes you have classes that only contain methods (operations). It depends on what the Java class is supposed to do.
Defining a Class in Java
All it takes to define a class in Java is this:
This defines a public Java class called MyClass . The class has no fields, constructors or methods.
.java Files
The above class definition should be put in its own file named MyClass.java . Java files should be named the same as the name of the class they contain, with the .java as file name extension. Make sure you keep the same uppercase and lowercase characters from the class name in the file name too.
Only put a single class definition in each Java file, unless your class contains inner classes of some kind. Inner classes are covered in my Java nested classes tutorial.
Class With Fields
As mentioned earlier, a Java class can contain data in the shape of variables. Variables that belong to the class are typically called «fields».
The next example shows a Java class which is to model a car. Therefore the class has named Car and has three fields. Here is the Java class in code:
This code defines a Java class named Car. The Car class has three fields. The Car class has no methods. Only field declarations. Fields are described in more detail in the text on Java fields.
Class With Constructor
A Java class can have a constructor. A constructor is a special method that is called when an object of the given class is created (explained later). The purpose of a constructor is to initialize the fields in the class. The fields are also called the «internal state». Here is an example of a Java class with two constructors:
public class Car < public String brand = null; public String model = null; public String color = null; public Car() < >public Car(String theBrand, String theModel, String theColor) < this.brand = theBrand; this.model = theModel; this.color = theColor; >>
The constructors are the two methods that have the same name as the class, and which have no return type specified. The first constructor takes no parameters, and the second takes 3 parameters. The constructor that takes 3 parameters stores the values of these parameters in the fields of the created object. Constructors are covered in more detail in my Java constructors tutorial .
Class With Methods
A Java class can also contain operations. These operations are typically called methods. A Java method contains Java instructions that typically perform some operations on a field in the class, or on one of the parameters (also variables) values passed to the method when the method was called.
Here is the Java class, Car example from the previous section with a method added:
In the class definition above I have added a setColor() method. When called, this method sets the internal color variable (field) to a new value. Methods are described in more detail in the text on methods.
Class With Nested Class
As mentioned earlier, you can define a nested class inside another Java class. Here is an example of defining a nested class inside a Java class:
In the example above, the outer class is called MyClass and the nested class is called MyNestedClass . Neither of the classes in this example has any fields or methods, but both the outer and nested class could have as many fields and methods as you see fit. You can read more about nested classes in my tutorial about nested classes in Java
Classes and Objects
A Java class is a template for how objects of that class looks. In other words, the Car class in the previous section is a template for how Car objects look.
To create objects of a certain class, you use the new keyword. Here is an example:
Car car1 = new Car(); Car car2 = new Car(); Car car3 = new Car(); car1.setColor("red"); car2.setColor("green"); car3.setColor("blue");
This example creates 3 Car variables, and assign a new instance of the Car class to each variable. Each variable now references a Car object. Each variable references a different Car object. Such objects are also called instances. If you change the fields of one object, the fields of other objects are not changed. Thus, the fields of different objects (even of the same class) can vary independently of each other.
After creating the 3 Car objects, the setColor() method is called on each object. Now the color (represented as a text) is set individually for each Car object.
Creating an object of a certain class is also called «instantiating» an object. The object is thus also called an «instance» of the given class. For instance, each of the Car objects above are also called an instance of the Car class, or simply «Car instances».
Further Concepts for Java Classes
What you have seen in this text only covers the very basics of Java classes. You need to learn about fields, constructors, methods nested classes, abstract classes, inheritance, access modifiers and interfaces too. All of these concepts are discussed in their own texts.
Lesson: A Closer Look at the «Hello World!» Application
Now that you’ve seen the «Hello World!» application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:
The «Hello World!» application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you’ve finished reading the rest of the tutorial.
Source Code Comments
/** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp < public static void main(String[] args) < System.out.println("Hello World!"); // Display the string. > >
Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:
/* text */ The compiler ignores everything from /* to */ . /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */ . The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc , see the Javadoc™ tool documentation . // text The compiler ignores everything from // to the end of the line.
The HelloWorldApp Class Definition
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp public static void main(String[] args) < System.out.println("Hello World!"); // Display the string. >>
As shown above, the most basic form of a class definition is:
The keyword class begins the class definition for a class named name , and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.
The main Method
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp < public static void main(String[] args) System.out.println("Hello World!"); //Display the string. > >
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order ( public static or static public ), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose «args» or «argv».
The main method is similar to the main function in C and C++; it’s the entry point for your application and will subsequently invoke all the other methods required by your program.
The main method accepts a single argument: an array of elements of type String .
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:
The «Hello World!» application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist.
System.out.println("Hello World!");
uses the System class from the core library to print the «Hello World!» message to standard output. Portions of this library (also known as the «Application Programming Interface», or «API») will be discussed throughout the remainder of the tutorial.
Java Class Example
You may also like
Calculate Rectangle Perimeter using Java Example
Swap Numbers Java Example
Java Factorial Using Recursion Example
Swap Numbers Without Using Third Variable Java Example
Calculate Circle Perimeter using Java Example
Hello World example
Calculate Rectangle Area using Java Example
Calculate Circle Area using Java Example
Find Largest and Smallest Number in an Array Example
Even Odd Number Example
Reverse Number using Java
Java Factorial Example
13 Comments
Cancel reply
Im not sure if you still need this answered, but ill answer it for others who might see this in the future date. You cannot directly alter other class’s variable when it is set as private, so if you create an class object in the main class, and have to set the name, you can’t just do objName.name = “name”. you need to call the setName function like objName.setName(“name”);, as setName function itself is set public so anything outside of its scope can use the function freely. This is necessary when you don’t want name variable accessible freely, where many things can go wrong if you do. imagine if you have class with variables that require accurate information, but the variables are not set private and something accessed it by accident, altering it.
hi i am new in this class java program.. can someone help me to how to ”create a program that shows my Name, age and location??”please help me