Search⌘ K
AI Features

Classes in Java

Explore how to define and structure classes in Java by creating files, adding properties, and writing methods. Understand how to use Java packages and apply syntax conventions for effective object-oriented programming.

Defining a Java class

To define a new class, create a new file named Classname.java. For example, to create a Dragon class, we will first create a file named Dragon.java, as shown in the following code widget.

Java
import java.util.*;
public class Dragon{
// class variables
public static void main(String[] args) {
// driver code
}
}

In this case, the class does not have a package. If it did, we would have declared it in the first line and stored the file in the same directory structure of the package.

The first line above imports everything in the java.util package. This includes List, ArrayList, Map, and HashMap for example. Then, we declare a “Dragon” class. The above code will output “Succeeded” since there are no functions for the driver code to print anything else.

Properties and methods

Next, we might want to add some properties and methods to our class. A property is a value associated with a particular object. A method is a block of code in a class.

Java
public class SmallClass {
String name;
String getname() {return name;}
void print() {System.out.println(name);}
public static void main(String[] args) {
SmallClass c = new SmallClass();
c.name = "Henry";
System.out.println(c.getname());
c.print();
}
}

In the above code, name is a String property, and getName and print are methods. The method getName returns a String (the name) and print uses the built-in System class to print out the name to the standard output stream.

Let’s make a simple class below!

Java
public class Details{
String name;
int age;
String gender;
String sentence(){
String det = "Hello, my name is " + name + ". I am " + age + " years old. I am a " + gender + ".";
return det;
}
public static void main(String[] args) {
//declaring an object of the class
Details myObj = new Details();
//assigning values
myObj.name = "Luke";
myObj.age = 16;
myObj.gender = "Male";
//printing name and age
System.out.println(myObj.name);
System.out.println(myObj.age);
//Calling function to print all details
System.out.println(myObj.sentence());
}
}

The above class Details, takes three variables, name, age, and gender and displays them in a sentence form.

The sentence() function returns the sentence made from the three values. It is then printed in main().