Monday, October 24, 2011

WALKTHROUGH:TNB Java Tut 42 -"toString" [VIDEO] [SOURCE CODE]

This is a full walk-through of Java Tutorial 42 by TheNewBoston. Each walk-through includes:
  • Embedded Video Tutorial
  • Text Transcript of the tutorial broken down into steps.
  • Source code
  • Visual Breakdown of the code
In this walk-through you will learn about using the "toString" method, a very useful method used to give any object a default string representation.


Step 1.Create a class and name it "stringDinger"
 public class stringDinger {  
 }  
inside of the "stringDinger" class:

Step 2.Create 3 int vars(month, day, year)
  private int month;  
  private int day;  
  private int year;  

Step 3.Create a constructor for the "stringDinger" class that accepts 3 parameters.
 public stringDinger(int m,int d,int y){  
inside of the stringDinger constructor:

Step 4.Set each of the incoming parameters to their corresponding variables:
  month=m;  
   day=d;  
   year=y;  

Step 5.create a print function statement that prints the sentence "the constructor for this is %s\n , this"(note: "using "this" in this case will equal whatever you're "toString" method returns )
  System.out.printf("the constructor for this is %s\n",this);  
end of stringDinger constructor.

Step 6.Create a "toString" method that returns the variables formated like this : "month/day/year":
  public String toString(){  
   return String.format("%d/%d/%d",month,day,year);  
  }  
end of "stringDinger" class

Step 7.Create a new class with a main method, name the class "useTheDinger"
 class useTheDinger{  
  public static void main(String[] args){  
 }  
 }  
inside the  main method of the "useTheDinger" class:

Step 8.Create a stringDinger object with the parameters 4,5,2011
  stringDinger theDingerSpeaks = new stringDinger(4,5,6);  

End of Tutorial
 TNB Java Tut 46 Complete Source Code 


"stringDinger" Class

 public class stringDinger {  
  private int month;  
  private int day;  
  private int year;  
  public stringDinger(int m,int d,int y){  
   month=m;  
   day=d;  
   year=y;  
   System.out.printf("the constructor for this is %s\n",this);  
 }  
  public String toString(){  
   return String.format("%d/%d/%d",month,day,year);  
  }  
 }  

"useTheDinger" Class

 class useTheDinger{  
  public static void main(String[] args){  
   stringDinger theDingerSpeaks = new stringDinger(4,5,6);  
   System.out.println(theDingerSpeaks.toString());  
  }  
 }  

3 comments:

Post a Comment

 
;