The Solution3:15 with Ben Deitch
See how I solve the challenge!
All right, how did you do? 0:00 Don't worry if everything didn't click right away. 0:02 That's totally normal and it certainly happened to me when I was learning Java. 0:05 Any who, here's how I solved the problem. 0:09 First, we create a new class named Cow. 0:12 Then we need to add a closing bracket down at the bottom. 0:18 Next, we will create a private string variable called 0:23 name private String name ,don't forget the semicolon. 0:27 And to make sure that we will never able to change it once it 0:32 is been set ,we'll also make it final. 0:35 For step three, we need to add a constructor that takes on a string 0:41 argument and use this string argument to populate our name variable. 0:45 So let's type public Cow, we'll add the string 0:51 parameter And then enter brackets. 0:56 And inside the function, We should set this.name = name. 1:03 In this case, this.name refers to the name on our Cow object. 1:12 And name here refers to the name parameter. 1:18 You can use different names if you'd like, but 1:21 this is a fairly normal way of doing it. 1:24 For step four, we need to create a getter to return the name of the Cow. 1:26 This function will be returning a string. 1:31 So we'll start with a return value and then the name of the function, 1:34 which would be get followed by the name of the variable, hich is name. 1:39 Inside this function, all we need to do is return the name. 1:47 Then let's save the file and move over to main.java. 1:52 Over in main.java, let's start by creating a new cow named Larry. 1:56 Cow cow = new Cow, and for the name argument, pass in Larry. 2:01 For the last step, we just need to print out the name of our Cow object. 2:12 Let's type console and use the printf function to print it out. 2:16 And while we can just print the name, since this is an example, 2:21 I'll go ahead and use complete sentences. 2:25 The cow is named, and we'll use %s for our place holder. 2:28 Then add a period. 2:34 I'll also add %n to give us a new line in our console. 2:36 That way it'll be a little easier to read. 2:40 Then let's add a closing quotation mark. 2:43 And for the parameter to fill in our %s, 2:46 let's use cow.getName to retrieve the name of our cow. 2:48 Finally, we just need to run the program. 2:55 If you don't remember how to do this, start by clearing the screen. 2:58 Then you'll need to compile it, And use the java command to run it. 3:03 And there we go. 3:12 The cow is named Larry. 3:13
You need to sign up for Treehouse in order to download course files.Sign up