Use of ‘this’ in a class – Java #58

*Watch copying and pasting the quotation marks, you may have to retype them to avoid an error

Using ‘this’ inside of class makes naming variables easier and your code easier to read

class containing this screenshot:

————-beginning of source code of class containing this————

package dagbaComputers;

public class SampleClass
{

private String custName;//string that will hold customer name inside this class

//Function that will save the current customer’s name
public void customerId (String custName)
{
//Saving customer name for this object/ all functions of it
this.custName = custName;
}
//end of customerId

//Function that will print out a greeting
public String helloStatement(String custName)
{
//adding the customer’s name to a greeting
String greeting = (“Happy 4th ” + custName + “!”);

return greeting;//returning the greeting
}
//end of helloStatement

}//end of SampleClass

————-end of source code of class containing this—————-

—————–screenshots of main function————————–

———beginning of main source code——————-

//Programmer: Akinwale Owi
//Company: Dagba Computers
//Program: Use of’this’ in a class

//beginning of program
package dagbaComputers;

import java.util.Scanner;

public class DagbaSamples {

public static void main(String[] args)
{
//creating scanner
Scanner identify = new Scanner(System.in);

//creating first SampleClass object
SampleClass sampleObject = new SampleClass();

//creating variables that will hold the users’ names
String userID, secondUserID;

//asking first customer for name
System.out.println(“Please enter your name”);

//saving the first user’s name
userID = identify.nextLine();

//printing out helloStatement for first object
System.out.printf(“” + sampleObject.helloStatement(userID) + “\n”);

//creating second object
SampleClass secondObject = new SampleClass();

//asking second customer for name
System.out.printf(“please enter your name” + “\n”);

//saving the second user’s name
secondUserID = identify.nextLine();

//printing out helloStatemnt second object
System.out.printf(sampleObject.helloStatement(secondUserID) + “\n”);

}//end of main function

}//end of class DagbaSamples(contains main function)
———-end of main source code————————

—————-output screenshot———————-

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: