Multiple methods and instances

import java.util.Scanner;

class jamesprogram {

	public static void main(String args[]){
		Scanner myinput = new Scanner(;
		cat catObject = new cat();
		System.out.println("Enter your first friends name: ");
		String temp = myinput.nextLine();

The above program uses methods from the cat class, so we create a new object of that class so we can use the methods within the cat class.

We pass the string temp (which is text captured by our scanner), and passes it to the setName method in the cat class. Our catObject now has a name that we’ve passed to it. We then execute the saying() method in the cat class.

public class cat {
	// private: only the methods inside this class can 
	// read and change this variable
    private String friendsName;

    public void setName(String name){
    // String below means this method below is 
    // going to return a string, if it's to return
    // nothing you put void
    public String getName(){
    	return friendsName;
    public void saying(){
    	// printf uses %s as a string marker, and this
    	// string is filled with the content of getName()
    	System.out.printf("Your first friend was %s", getName());

This outputs:

Enter your first friends name:
Your first friend was james

Leave a Reply