Creating Your First Java Classes
- Features of the Java Programming Language
- Java Program Types
- Saving a Java Class
- Compiling a Java Class
- Running a Java Class
- Modifying a Java Class
Explanations to week content
Creating Methods
A method is a program module that contains a series of statements that carry out a task. You have already seen Java classes that contain a main() method. The main() method can execute additional methods. To execute a method, you invoke or call it. In other words, a calling method makes a method call, which invokes a called method. The calling method is also known as a client method; a called method provides a service for its client. Any class can contain an unlimited number of methods, and each method can be called an unlimited number of times.
What is more important is that a method is easily reusable. In other words, you do the work once, and then you can use the method many times.
A method must include the following:
A method header—A method’s header provides information about how other methods can interact with it. A method header is also called a declaration.
A method body between a pair of curly braces—The method body contains the statements that carry out the work of the method. A method’s body is called its implementation. Technically, a method is not required to contain any statements in its body, but you usually would have no reason to create an empty method in a class.
Sometimes, while developing a program, the programmer creates an empty method as a placeholder, and fills in the implementation later. An empty method is called a stub.
An optional access specifier—The access specifier for a Java method can be any of the following modifiers: public, private, protected, or if left unspecified (default). Most often, methods are given public access.
Endowing a method with public access means any class can use it.
Java is an object oriented programming and hence has encapsulation which can be used to hide the unwanted details.
Java provides entities called “Access Modifiers or access specifiers” that help us to restrict (encapsulate) the scope or visibility of a package , class, constructor, methods, variables, or other data members.
Types Of Access Modifiers In Java
Java provides four types of access specifiers that we can use with classes and other entities.
These are:
Default
Whenever a specific access level is not specified, then it is assumed to be ‘default’. The scope of the default level is within the package.
Public
This is the most common access level and whenever the public access specifier is used with an entity, that particular entity is accessible throughout from within or outside the class, within or outside the package, etc.
Protected
The protected access level has a scope that is within the package. A protected entity is also accessible outside the package through inherited class or child class.
Private
When an entity is private, then this entity cannot be accessed outside the class. A private entity can only be accessible from within the class.
These can be summarized in the table below.
Access Specifier | Inside Class | Inside Package | Outside package subclass | Outside package |
---|---|---|---|---|
Private | Yes | No | No | No |
Default | Yes | Yes | No | No |
Protected | Yes | Yes | Yes | No |
Public | Yes | Yes | Yes | Yes |
We will demonstrate these later.
In addition, like main(), any method that can be used without instantiating an object requires the keyword modifier static.
The return type for the method—A method might return a value, or send it back, to its calling method. If so, the method’s return type is the data type of the returned data. A method that returns no data has a return type of void.
The method name—The name can be any legal identifier. That is, it must be one word with no embedded spaces, and cannot be a Java keyword.
A set of parentheses—The parentheses optionally might contain data to be sent to the method. For example, when you write a main() method in a class, the parentheses in its header surround (String[] args).
Syntax:
access identifier return data type methodName(Input Data){
//Method codes come here
return result;// Returned value must be the same data type as the method data type
//If the method data type is void, nothing is returned
}
e.g if the access identifier is public and return data type is int and the input data are int a, int b, then applying the above syntax produces a method by name sum
public int sum(int a, intb){
return a+b;
}
if the above method(sum) will be used without instantiating an object, the method could be modified as:
public static int sum(int a, int b){
return a+b;
}
NOTE: There will be compilation error if you specify a return data type for the method but you are not returning the specified data type in your method.
PLACEMENT OF METHOD WITHIN A CLASS
You can place a method before or after the main method in the class.
Figure: Placement of methods in a class
The main() method executes first in an application, no matter where you physically place the main() method within its class. Remember that every Java application must contain a main() method, but each Java class is not required to contain one.
INVOKING A METHOD
A method is invoked either in the main method or other methods
A method is invoked by simply writing the name of the method and passing the required input if the method has input data but otherwise just the name of the method and two brackets ()
for example to invoke the above sum method, the syntax below could be written:
int a = 2;
int b = 3;
int c;
//the method can be invoked as
c = sum(a,b); //The return result is then stored in c
Demonstration
· displays WELCOME TO JAVA PROGRAMMING
· add two numbers and returns the result
· multiply two numbers and return the result
· takes a number and return the square of the number
· takes the radius of a circle and return the circumference
Sample Code
public class Mathematics {
final static double PI =3.142;
public static void main(String[] args) {
// TODO Auto-generated method stub
//Call the class methods
welcome();
int a = 5,b=7, c,d,e;
c = sum(a,b);
System.out.println(a+"+ "+b+" = "+c);
d = product(a,b);
System.out.println(a+"x "+b+" = "+d);
e = square(a);
System.out.println(a+"square = "+e);
double radius =2.5,circf;
circf = circumference(radius);
System.out.println("The circumference of a circle of radius "+radius+" is "+circf);
}
public static void welcome(){
System.out.println("WELCOME TO JAVA PROGRAMMING");
}
public static int sum(int a, int b){
return a+b;
}
public static intproduct(int a, int b){
return a*b;
}
public static intsquare(int a){
return a*a;
}
public static doublecircumference(double radius){
return 2*PI*radius;
}
}
Declaring Objects and Using Their Methods
An object is an instance of a class.
An object is declared with the syntax below:
ClassName objectName = new ClassName();
Example, if there is a class by name Employee, an object of the class could be declared as:
Employee employee = new Employee();
From the above example, employee is the object of the class, Employee.
You can also declare the object before creating the instant of the class. Thus the syntax above could also be written as:
Employee employee;
employee = new Employee();
Most classes you create have multiple data fields and methods.
For example the Employee class may have the following data:
String firstname;
String lastname;
String phone;
String employee_id;
double salary;
The Employee class may also have a method, getSalary which returns the salary value of the employee.
The value of these variables are set either by using set methods or constructors. The values can be accessed using the get methods.
The Set Methods
The set method has the same syntax of writing a method except that it has an argument (input parameter) which set the value of the data you want to set.
Most set method names begin with the first word set and the rest of the name is base on the variable being set. It also has the void data type since it returns no output.
For example we can write a set method for the above variables for the Employee class.
public void setFirstName(String fn){
firstname= fn;
}
public void setLastName(String ln){
lastname= ln;
}
public void setPhone(String phoneNumber){
phone= phoneNumber;
}
public void setEmployeeId(String employeeId){
employee_id= employeeId;
}
public void setSalary(double employeeSalary){
salary= employeeSalary;
}
NOTE
If you decide to give the input data in the set method the same name as the variable being set, you will need to add the this keyword to the variable being set to differentiate it from the input data.
Thus the set syntax will then be:
this.variableName = variableName;
For example if we decide to use the same input data as the variables being set, the above set methods will then have to be modified as follows:
public void setFirstName(String firstname){
this.firstname= firstname;
}
public void setLastName(String lastname){
this.lastname= lastname;
}
public void setPhone(String phone){
this.phone= phone;
}
public void setEmployeeId(String employee_id){
this.employee_id= employee_id;
}
public void setSalary(double salary){
this.salary= salary;
}
The Get Method
The get methods return the data set either by the set methods or by a constructor. This means that all get methods has a return output and the data type of the method should be the same as the data type of the variable whose value is being returned. The get method name also begin with the first word get and followed by a name relating to the data whose value is being accessed. The get method doesn’t have any argument (no input data).
The get methods for the above set methods will then be:
public String getFirstName(){
return firstname;
}
public String getLastName(){
return lastname;
}
public String getPhone(){
return phone;
}
public String getEmployeeId(){
return employee_id;
}
public double getSalary(){
return salary;
}
Demonstration
Create a new project and name it week_3_object_example
Add the class Main with the public static void main ticked during the addition on the form.
Add a new class by name Employee. This time don’t tick the public static void main on the form.
1. Declare the variables for the Employee class
2. Write the set and get methods
3. Create an object of the Employee class in the main class.
4. Save your project
Accessing the Methods Of The Class
Syntax:
objectName.methodCall;
For instance to use the setFirstName method to set thefirst name for the Employee object created, the syntax below is written:
employee.setFirstName(“Godwin”);
Set the data fields for the employee object created inthe main.
Sample Code:
employee.setFirstName(“Godwin”);
employee.setLastName(“Ashong”);
employee.setPhone(“+233200000000”);
employee.setEmployeeId(“20190012”);
employee.setSalary(2000);
Now let’s access our set names.
String firstname = employee.getFirstName();
String lastname = employee.getLastName();
String phone = employee.getPhone();
String employee_id = employee.getEmployeeId();
double salary = employee.getSalary();
Display The Values To Confirm They Are Set
System.out.println(“Employee First Name: ”+firstname);
System.out.println(“Employee Last Name: “+lastname);
System.out.println(“Employee Phone: “+phone);
System.out.println(“Employee ID: “+employee_id);
System.out.println(“Employee Salary: “+salary);
You can as well access the value of a variable in the class by the object name then a full stop then the variable name.
Syntax
objectName.variableName;
For example the first name of the employee object can be accessed as:
employee.firstname;
So to display directly we could as well write:
System.out.println(“Employee First Name: ”+employee.firstname);
Run your project and see the output
Complete Sample Code
Employee.java
package week_3_object_example;
public classEmployee {
//Data Fields
publicString firstname,lastname,employee_id,phone;
public double salary;
//Methods to set data fields
public voidsetFirstName(String firstname){
this.firstname = firstname;
}
public voidsetLastName(String lastname){
this.lastname = lastname;
}
public voidsetEmployeeID(String employee_id){
this.employee_id = employee_id;
}
public voidsetPhone(String phone){
this.phone = phone;
}
public voidsetSalary(double salary){
this.salary = salary;
}
//Methods to get data
publicString getFirstName(){
return firstname;
}
publicString getLastName(){
return lastname;
}
publicString getEmployeeID(){
return employee_id;
}
publicString getPhone(){
return phone;
}
public doublegetSalary(){
return salary;
}
}
Main.java
packageweek_3_object_example;
public class Main{
public static voidmain(String[] args) {
// TODOAuto-generated method stub
//Create theEmployee object
Employee employee = newEmployee();
//Set the datafields
employee.setFirstName("Godwin");
employee.setLastName("Ashong");
employee.setEmployeeID("2019001");
employee.setPhone("+233200000000");
employee.setSalary(2000);
//Get the setvalues
String firstname = employee.getFirstName();
String lastname = employee.getLastName();
String phone = employee.getPhone();
String employee_id = employee.getEmployeeID();
double salary = employee.getSalary();
//Display theset data values
System.out.println("EmployeeFirst Name: "+firstname);
System.out.println("EmployeeLast Name: "+lastname);
System.out.println("EmployeePhone: "+phone);
System.out.println("EmployeeID: "+employee_id);
System.out.println("EmployeeSalary: "+salary);
}
}
An Introduction to Using Constructors
When you create a class, such as Employee, andinstantiate an object with a statement such as the following, you are actuallycalling the Employee class constructor that is provided by default by the Javacompiler:
Employee employee = new Employee();
A constructor establishes an object; a defaultconstructor is one that requires no arguments.
A default constructor is created automatically by theJava compiler for any class you create whenever you do not write your own constructor.
When the prewritten, default constructor for theEmployee class is called, it establishes one Employee object with theidentifier provided.
The automatically supplied default constructor provides the following specific initial values to anobject’s data fields:
If you do not want each field in an object to hold these default values, or if you want to perform additional tasks when you create an instance of a class, you can write your own constructor.
Any constructor you write must have the same nameas the class it constructs, and constructors cannot have a return type.You never provide a return type for a constructor— not even void. Normally, you declare constructors to be public so that other classes can instantiate objects that belong to the class. When you write a constructor for a class, you no longer have access to the automatically created version.
Constructors are usually used to initialize the data fields instead of using the set methods.
You can write any Java statement in a constructor. Although you usually have no reason to do so, you could display a message from within a constructor or perform any other task.
We can modify our Employee class to use constructor toset the data fields instead of the set methods.
Create a new class and name itEmployeeConstructorExample.
Copy and paste the data fields from the Employee classto the EmployeeConstructorExample class.
Copy the get methods too and paste into theEmployeeConstructorExample class.
Now lets write the constructor for theEmployeeConstructorExample class
Syntax:
public class ClassName{
//datafields are declared here
publcClassName(input data to set the data fields){
//Set the data fields. Use the thiskey word in case data fields are the same as input data
//You can display a message thatconstructor created or perform a task Although you
//usually have no reason to do so
}
}
Now let’s write the constructor for our EmployeeConstructorExample class
public class EmployeeConstructorExample{
//Declarethe data fields
public Stringfirstname,lastname,employee_id,phone;
publicdouble salary;
//Createthe constructor
publicEmployeeConstructorExample(String firstname,String lastname, String
employee_id,String phone, double salary){
this.firstname= firstname;
this.lastname = lastname;
this.employee_id = employee_id;
this.phone = phone;
this.salary = salary;
}
}
Creating instance of a class with a constructor
Syntax:
ClassName objectName = new ClassName(data input for the constructor);
For instance the object of the EmployeeConstructorExample class can be created as:
EmployeeConstructorExample employee_2 = newEmployeeConstructorExample(“Godwin”,”Ashong”,”2019001”,”+233200000000”,2000);
Now you can access your data fields with the getmethods as explained above.
Now create an object for the classEmployeeConstructorExample in the Main class and name it employee_2 and assign values to your input data fields for the constructor of that class.
Access the set data fields just like we did for theEmployee object (employee) and display the values.
Complete Sample Codes
EmployeeConstructorExample.java
package week_3_object_example;
public class EmployeeConstructorExample {
//Data Fields
publicString firstname,lastname,employee_id,phone;
public double salary;
//Create the constructor
public EmployeeConstructorExample(Stringfirstname,String lastname,
String employee_id,String phone, double salary){
this.firstname = firstname;
this.lastname = lastname;
this.employee_id = employee_id;
this.phone = phone;
this.salary = salary;
}
//Get Methods
publicString getFirstName(){
return firstname;
}
publicString getLastName(){
return lastname;
}
publicString getEmployeeID(){
return employee_id;
}
publicString getPhone(){
return phone;
}
public doublegetSalary(){
return salary;
}
}
Main.java
package week_3_object_example;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Create the Employee object
Employee employee = new Employee();
//Set the data fields
employee.setFirstName("Godwin");
employee.setLastName("Ashong");
employee.setEmployeeID("2019001");
employee.setPhone("+233200000000");
employee.setSalary(2000);
//Get the set values
String firstname = employee.getFirstName();
String lastname = employee.getLastName();
String phone = employee.getPhone();
String employee_id = employee.getEmployeeID();
double salary = employee.getSalary();
//Display the set data values
System.out.println("Employee First Name: "+firstname);
System.out.println("Employee Last Name: "+lastname);
System.out.println("Employee Phone: "+phone);
System.out.println("Employee ID: "+employee_id);
System.out.println("Employee Salary: "+salary);
//Creating object of a class with a constructor
EmployeeConstructorExample employee_2 = new EmployeeConstructorExample("Godwin","Ashong","2019001","+233200000000",2000);
//Get the values and Display
String firstname_2 = employee_2.getFirstName();
String lastname_2 = employee_2.getLastName();
String phone_2 = employee_2.getPhone();
String employee_id_2 = employee_2.getEmployeeID();
double salary_2 = employee_2.getSalary();
//Display the set data values
System.out.println("Second Employee First Name: "+firstname_2);
System.out.println("Second Employee Last Name: "+lastname_2);
System.out.println("Second Employee Phone: "+phone_2);
System.out.println("Second Employee ID: "+employee_id_2);
System.out.println("Second Employee Salary: "+salary_2);
}
}
Access Modifiers Demonstration
Create a project and create the following packages and their classes as shown in the below below:
Package
default_example
Clases
DefaultExampleClass
package default_example;
public class DefaultExampleClass {
String fn,ln;
void setFn(String fn) {
this.fn= fn;
}
String getFn() {
return fn;
}
void setLn(String ln) {
this.ln= ln;
}
String getLn() {
return ln;
}
String getFullName() {
return getFn()+" "+getLn();
}
}
Main
package default_example;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DefaultExampleClass ex = new DefaultExampleClass();
ex.setFn("Godwin");
ex.setLn("Ashong");
System.out.println("First Name:"+ex.getFn());
System.out.println("Last Name:"+ex.getLn());
System.out.println("Full Name:"+ex.getFullName());
}
}
Package
Main
Classes
Main
package main;
import private_example.PrivateExampleClass;
import protected_example.ProtectedExampleClass;
import public_example.PublicExampleClass;
import default_example.DefaultExampleClass;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Calling methods outside their package
//Public modifier
PublicExampleClass ex_1 = new PublicExampleClass();
ex_1.setFn("Godwin");
ex_1.setLn("Ashong");
System.out.println("First Name:"+ex_1.getFn());
System.out.println("First Name:"+ex_1.fn);
System.out.println("Last Name:"+ex_1.getLn());
System.out.println("Last Name:"+ex_1.ln);
System.out.println("Full Name:"+ex_1.getFullName());
//Private modifier
PrivateExampleClass ex_2 = new PrivateExampleClass();
ex_2.setFn("Godwin");
ex_2.setLn("Ashong");
System.out.println("First Name:"+ex_2.getFn());
System.out.println("First Name:"+ex_2.fn);
System.out.println("Last Name:"+ex_2.getLn());
System.out.println("Last Name:"+ex_2.ln);
System.out.println("Full Name:"+ex_2.getFullName());
//Protected modifier
ProtectedExampleClass ex_3 = new ProtectedExampleClass();
ex_3.setFn("Joseph");
ex_3.setLn("Martey");
System.out.println("First Name:"+ex_3.getFn());
System.out.println("First Name:"+ex_3.fn);
System.out.println("Last Name:"+ex_3.getLn());
System.out.println("Last Name:"+ex_3.ln);
System.out.println("Full Name:"+ex_3.getFullName());
//Default Example
DefaultExampleClass ex_4 = new DefaultExampleClass();
ex_4.setFn("Mary");
ex_4.setLn("Kpodo");
System.out.println("First Name:"+ex_4.getFn());
System.out.println("First Name:"+ex_4.fn);
System.out.println("Last Name:"+ex_4.getLn());
System.out.println("Last Name:"+ex_4.ln());
System.out.println("Full Name:"+ex_4.getFullName());
}
}
Package
private_example
Classes
PrivateExampleClass
package private_example;
public class PrivateExampleClass {
private String fn,ln;
public void setFn(String fn) {
this.fn= fn;
}
public String getFn() {
return fn;
}
public void setLn(String ln) {
this.ln= ln;
}
private String getLn() {
return ln;
}
public String getFullName() {
return getFn()+" "+getLn();
}
}
Main
package private_example;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
PrivateExampleClass ex = new PrivateExampleClass();
ex.setFn("Godwin");
ex.setLn("Ashong");
System.out.println("First Name:"+ex.getFn());
System.out.println("Last Name:"+ex.getLn());
System.out.println("Full Name:"+ex.getFullName());
}
}
Package
protected_example
Classes
ProtectedExampleClass
package protected_example;
public class ProtectedExampleClass {
protected String fn,ln;
protected void setFn(String fn) {
this.fn= fn;
}
protected String getFn() {
return fn;
}
protected void setLn(String ln) {
this.ln= ln;
}
protected String getLn() {
return ln;
}
public String getFullName() {
return getFn()+" "+getLn();
}
}
Main
package protected_example;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProtectedExampleClass ex = new ProtectedExampleClass();
ex.setFn("Godwin");
ex.setLn("Ashong");
System.out.println("First Name:"+ex.getFn());
System.out.println("Last Name:"+ex.getLn());
System.out.println("Full Name:"+ex.getFullName());
}
}
Package
public_example
Classes
PublicExampleClass
package public_example;
public class PublicExampleClass {
public String fn,ln;
public void setFn(String fn) {
this.fn= fn;
}
public String getFn() {
return fn;
}
public void setLn(String ln) {
this.ln= ln;
}
public String getLn() {
return ln;
}
public String getFullName() {
return getFn()+" "+getLn();
}
}
Main
package public_example;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
PublicExampleClass ex = new PublicExampleClass();
ex.setFn("Godwin");
ex.setLn("Ashong");
System.out.println("First Name:"+ex.getFn());
System.out.println("Last Name:"+ex.getLn());
System.out.println("Full Name:"+ex.getFullName());
}
}
If you hover on the error explanation, you will see that all the errors are not visible errors because of the access modifiers for private, protected and default (if not access modifier set).
For public there was no error because public variables and methods can be accessed every where (in the package or outside the package)
Figure: not visible error message
Assignment
Create two classes for student. Use set methods to set the data fields for one of the classes and constructor to set the data fields of the other. Both classes must be in the same project.