How Can We Help?
Objects and Classes in Java
Introduction
Java features objects and classes from its initial versions as an object-oriented language. The Class is conceived as a prototype, draft, or idea for its instances. You can have integers, real numbers, and strings. Still, you also have classes for cars, motorcycles, people, buildings, employees, students, courses, bank accounts, and any types that are essential to solving a given problem.
Classes specify data and behavior, both their own and the objects created from them. The class has two parts: attributes and methods. Attributes describe what a class is. The methods describe what the class does.
Using the prototype that the class represents, you can create any number of objects, each of which is an instance of the class. Different objects of the same class have the same attributes and methods, but the attribute values will generally differ. E.g., all people have some eye color, but it varies from person to person.
On the other hand, an object of a class has the same methods as other objects of that class, but the methods depend on the values of their arguments and object attributes. This is reflected in the runtime shape of the object. Each object has a separate block of memory for its attributes, but the memory in which the methods are recorded is common to all objects of a given class.
Other object-oriented paradigms supported in Java include encapsulation, abstraction, polymorphism, inheritance. All these concepts will be elaborated on in the further articles.
Classes in Java
In this section, we will not try to write a complete program; instead, we will concentrate on the design of objects that will contain data for each student. The class representing the design of that type of object will be called the Student.
If we were to design a clock, we would start with the idea of how to construct an interface, i.e., a set of operations that the clock needs to perform. After that, we would work on the implementation of the interface, i.e., how to arrange the items inside the case to ensure the required functionality.
Similarly, first defining a Student class is deciding which operations will be associated with a Student object. To maintain the simplicity of the example, we will include a limited set of operations:
- It will be necessary to allow the students to have an Id. This action will normally take place at the enrollment.
- Defining and changing the study program (curriculum) will be necessary.
- It will be necessary to provide a way for the object to return the student’s name so that the program can examine which student the corresponding object belongs to.
- It will be necessary to enable the printing of student data on the screen. We will provide a display method that will do this.
- It will be necessary to calculate and print a student’s GPA on the screen.
- It will be necessary to create new objects of the Student type. Each time it is created, it will be necessary to provide information about the student, e.g. name, study program (curriculum), etc.
Example of a class Student, containing three attributes (name, Id, curriculum) and two methods (setID, getName):
Syntax
public class Student {
String name;
int Id;
String curriculum;
void setId() {
}
void getName() {
}
}
Objects in Java
The objects are instances of a particular class. The class itself must be instanced to be used. All objects built based on the same design belong to the same class.
The user will answer the question “What is an object” with “I don’t know what it consists of, but I know its interface and what I can do with it”. The designer will respond with: “It is made up of variables and methods that interact to realize the interface (functionality) of the object”.
The following program creates a new instance of the Student (studOne object), assigns values to its attributes (variables – name and Id), and prints the result.
Syntax
class Student{
String name;
int Id;
public static void main(String args[]) {
Student studOne = new Student();
studOne.name = "Michael";
studOne.Id = 730;
System.out.println(studOne.name + "is the student name, and " + studOne.Id + "is student’s ID");
}
}
Methods and Constructors in Java
The methods are class members that perform operations on (or with) the object. E.g., we saw that the ConsoleReader object has a method called ReadInt that uses that object to get the value that the user typed.
When we write the definition of the Student class, we will have a Set ID method that will set the student ID. This type of method is called the instance method to distinguish them from static methods that do not belong to any object (more on static methods later).
For the Student class – we can have a method for defining a student’s name and curriculum.
Method Syntax
public void setCurriculum(String p)
{
curriculum = p;
}
Constructors – these members are used to construct objects of a certain class. We will include one constructor in the Student class because otherwise it would not be possible to write a program that would use the objects of that class. Constructors are similar to methods in many ways.
The constructor always has a name identical to the class name. In this case, the constructor is called Student. The constructor has no indication of what it is returning, because it is obvious what it should return, and that is the object it creates.
Constructor can have any number of parameters. This one has three: student ID number, name and study program. It’s assumed here that the year of study will be 1 when the object is created:
Constructor Syntax
public Student(String id, String name, String curric)
{
idNo = id;
nme = name;
curriculum = curric;
year = 1;
}
Packages in Java
Packages are a way to organize classes in groups (to categorize them). They help to reduce problems with name conflicts. As the number of Java classes grows, so does the likelihood of using the class name same as another, leaving room for errors if you try to integrate multiple classes into a single program. Packages allow you to mask classes to avoid conflicts.
Packages can be used to identify classes. For example, if you implement a set of classes to accomplish a goal, you can name the package with a unique identifier that identifies you or your organization.
Packages also allow you to protect classes, variables, and methods more broadly than on a class-by-class basis, using the protected types of objects. We will talk more about package protection below.
To import a package of classes, use the import command, as we used through other previous examples. You can import an individual class this way:
Syntax
import java.util.Vector;
Examples
In the following example we will present all mentioned concepts:
- Creating a class Student with 4 attributes (Id, Name, Year, Curriculum)
- Creating an object: studentOne (in the main() method);
- Using methods: studyYear(), getName(), and setCurriculum() to define the particular attributes.
- Using method display() to display student’s attributes.
/* Student Class and Object example */
public class Student
{
private int id ; // Student ID
private String name; // student name
private String Curriculum; //Course of study
private int year; // Study year (1, 2, 3, 4).
/* Change curriculum in variable p */
public void setCurriculum(String p)
{
curriculum = p;
}
/* Increase study year by one */
public void studyYear()
{
year++;
}
/* Get Student’s name */
public String getName()
{
return name;
}
/* Display student information on the screen */
public void display()
{
System.out.println ("Student ID: " + id);
System.out.println ("Name: " + name);
System.out.println ("Curriculum: " + curriculum);
System.out.println ("Year: " + year);
}
public static void main(String args[])
{
/* Create object using constructor */
Student studOne = new Student();
studOne.id = 232;
studOne.name = “Peter”;
// Invoking methods for the object created
studOne.setCurriculum("Law");
studOne.studyYear( );
studOne.dispay();
}
Now we will present an example with two classes – Student and StudentTest. The Student class is a public class, and we will save this source file with the name Student.java.
The Student class has four instance variables – name, id, curriculum, and GPA. The class has one explicitly defined constructor, which takes a parameter.
import java.io.*;
public class Student{
String name;
int id;
String curriculum;
double gpa;
// This is the constructor of the class Student
public Student(String name) {
this.name = name;
}
// Assign the Id of the Student to the variable id.
public void studId(int studId) {
id = studId;
}
/* Assign the curriculum to the variable designation.*/
public void studCurriculum(String studCurric) {
curriculum = studCurric;
}
/* Assign the Gpa to the variable gpa.*/
public void studGpa(double studGpa) {
gpa= studGpa;
}
/* Print the Student details */
public void printStudent() {
System.out.println("Name: "+ name );
System.out.println("ID: " + id );
System.out.println("Curriculum: " + curriculum );
System.out.println("GPA: " + gpa);
}
}
The execution of the Java program always starts from the main() method. Together with the previous class Student – we now create the StudentTest class, which creates two instances of the class Student and invokes the methods for each object to assign values for each variable.
We save the following code in the StudentTest.java file.
import java.io.*;
public class StudentTest {
public static void main(String args[]) {
/* Create two objects using constructor */
Student studOne = new Student("Peter Black");
Student studTwo = new Student("Jade Green");
// Invoking methods for each object created
studOne.studId(232);
studOne.studCurriculum("Law");
studOne.studGpa(4.6);
studOne.printStudent();
studTwo.studId(373);
studTwo.studCurriculum("Economy");
studTwo.studGpa(4.2);
studTwo.printStudent();
}
}
When we will compile and run both classes – we will obtain the following output on the screen:
> javac Student.java
> javac StudentTest.java
> java StudentTest
Name:Peter Black
ID: 232
Curriculum: Law
GPA: 4.6
Name: Jade Green
ID: 373
Curriculum: Economy
GPA: 4.2
In this tutorial, you have learned What is a class and object? What are a constructor and methods? What is a package in Java?.
If you have an inquiry or doubt, don’t hesitate to leave them in the comment section. We are waiting for your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Java Tutorials List:
- Java tutorials list: access all Java Tutorials.