Multiple methods and instances

// jamesprogram.java
import java.util.Scanner;

class jamesprogram {

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

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.

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

    public void setName(String name){
		friendsName=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:
james
Your first friend was james

Leave a Reply