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.
We'll cover the following...
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.
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.
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!
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().