Friday, November 18, 2016

Inheritance and Polymorphism Revisited - Challenge



Start with the UML below.  You should try to implement this UML with a simple code not even looking at the code below.  See if you can successfully interpret the UML.


You should interpret the UML above and write the problem statement this UML solves.

You can compare your code to the code below or use it as a reference if you get stuck.

/** Animal class that is used as the super class with different modifiers to help understand inheritance
* @version 1.0.0.0
* @author Zoltan Szabo
*/
public class Animal{
    public int x=50;
    private int y=60;
    protected int z=70;
    int k=80;
  
    public static int XX=150;
    private static int YY=160;
    protected static int ZZ=170;
    static int KK=180;
  
/** Super class no-arg constuctor*/
   public Animal(){
      System.out.println("This is the superclass (Animal) constructor.");
   }

/** Public method in the superclass
* @return x public field from superclass
*/
   public int func1(){
        return x;  
   }

/** Private method in the superclass
* @return y private field from superclass
*/   private int func2(){
        return y;
   }

/** Protected method in the superclass
* @return z protected field from superclass
*/   protected int func3(){
        return z;
   }

/** Public method in the superclass
* @return k default field from superclass
*/   int func4(){
        return k;
   }
}

/**
*Cat class that is a child of the Animal class inherits public, protected, and default attributes and methods
*@version 1.0.0
*@author Zoltan Szabo
*/ public class Cat extends Animal{
/** SubSubClass1 class no-arg constuctor*/
   public Cat(){
      System.out.println("I\'m a Cat constructor.");
   }
}

/**
*Class that is a child of the Animal class inherits public, protected, and default attributes and methods
*@version 1.0.0
*@author Zoltan Szabo
*/

public class Dog extends Animal{

/** SubClass1class no-arg constuctor*/
   public Dog(){
      System.out.println("I'm a Dog constructor.");
   }
   public void doTrick(){
       System.out.println("I can roll over.");
    }
}

/** This simple application will help you understand polymorphism
* @version 1.0.0
* @author Zoltan Szabo
*/

public class AnimalsDemo{
    final static int INDEX=2;

/** application entry point to test inheritance of modifiers
* @param args as a String array for command argument input
*/

   public static void main(String[] args)   {

      Animal obj[]=new Animal[5];
      obj[0]=new Animal();
      obj[1]=new Dog();
      obj[2]=new Cat();
     /*
      * according to the java language specification, 3rd edition:
      * 6.6.8 Example: private Fields, Methods, and Constructors
      * A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
      * It is not inherited by subclasses.
      */
     //Instantiate one of each objects in an Animal array of objects
     //Display collar color for each animals and the length of the leash where it applies.
   }
}

Now take the initial code and extend the application to implement this UML.

 The output should look like this.



Wednesday, November 2, 2016

UML in BlueJ and Eclipse

Unified Modeling Language ( UML ) is the best way to design an application and to analyze an object oriented code.

Taking a code and easily turn it into a UML can be done with an IDE, but there are extensions for IDEs that do not support UML generation by default.  BlueJ has two extensions that can be used for this purpose.

BlueJ UML extensions video if you need it
https://youtu.be/e5h15mTvEP4

Copy the jar files into folder <BLUEJ_HOME>\lib\extensions

Class Card - A Better UML Extension - http://klassenkarte.steinhuber.de/
Con: No datatypes for attributes and parameters
Pro: Shows attributes

UML Extension - http://www.bluej.org/extensions/extensions.html 

Con: No attributes listed
Pro: Parameter and return value data types


 After adding the extensions, they will be available by right-clicking on the class you need to see its UML.


You can see the difference between the two extensions and decides witch one works for you.


At the end, you'll see that Eclipse does a much better job showing the UML based outline of the class and if you don't really need pretty graphics based UML, it will be the most complete UML with the least effort.



Greetings from a JAR

A typical simple application looks like this from a first year student taking Java for the first time.  the code works, but it is not college level, detail oriented, and user friendly application.  the beauty of modern programming languages is the same as the beauty of modern technology, it is easily adoptable and user friendly.  Java is an easy language to pick up and learn because of its documentation, so don't ignore what makes Java strong.

Modern applications are also user friendly and engaging, so make sure you create your own brand by being consistent in your coding and be nice to your users.  Give users a basic information about yourself and about the application, but most importantly welcome the users like thy are your guests.  there are many great applications that are out there, but you have to be unique in your application approach and don't let a user just leave after running your program.  Thank them for using your program and either tell them about your other applications, give them incentives to come back, or at least send them to your website.

public class SampleApp {
public static void main(String[] args) {
System.out.println("The number 10 raised to the power of 3 is: " + java.lang.Math.pow(10,3));    
System.out.println("Hello World");
}
}

Videos to use Greetings.jar in BlueJ and Eclipse

Greetings JAR BlueJ
https://youtu.be/F0-ClRhUZA4

Greetings JAR Eclipse
https://youtu.be/qK88J11N0VE


Greetings.jar file Download

So, that simple application can be embellished to make it fit to be called Java code and the branding can be done easily with custom classes.  Thus, in this project you'll learn how to use someone else's jar packaged classes in BlueJ and in Eclipse.  The classes are simple enough, so you can learn how to handle import statements, read documentations, and the concept of static methods.

All these simple suggestions will make you a better programmer and a consistent professional!

import rlc.zoltan.COSC.Welcome;
/**
 * Description
 * @author  Name
 * @version 1.0.0
 */
public class SampleApp {
    /**
     * Description
     * @param args string array from the command line
     * @return void
     * @throws Nothing is implemented
     */
    public static void main(java.lang.String[] args)     {
     //Let your users know that you appreciate them for choosing to use our application
     Welcome wmsg=new Welcome("Welcome to my course. I hope you'll enjoy it.");
     rlc.zoltan.COSC.MyCourse.InfoI();
     java.lang.System.out.println(wmsg);
 
    java.lang.System.out.println("The number 10 raised to the power of 3 is: " + java.lang.Math.pow(10,3));        java.lang.System.out.println("Hello World");
 
    //Keep your users engaged as they leave
    rlc.zoltan.COSC.Appreciate thanks=new rlc.zoltan.COSC.Appreciate();
    java.lang.System.out.println(thanks);
    }
}

Let me know if you need a copy of the Greetings.jar file that this example code was based on.  

Saturday, October 15, 2016

Base UML / Structured Logic of methods

Unified Modeling Language ( UML ) is a great way to visualize the relationships and interaction designs of objects, but it is not helpful for the structured design of the methods.  Thus, in this standard, we bring both together where we start with the UML and then add the structured logic for each one of the methods for clear communication of the design ( schema ) to the implementer ( coders ) like the architect communicates his/her design to the journeymen.

Remember design of the algorithm is our way of communication not a necessary evil or extra work.  Remember design is the third step before we start to program without it, it is not program design, just coding.  Reference for the programming life cycle  -  http://intro2cs-java.blogspot.com/2015/01/problem-to-execution-methodology.html


Friday, October 14, 2016

While Loop Summary Exercise

Run this summary code and you will know everything you need to know about while loop structures in Java.  Make sure to go to Java API and read about the classes and/or methods that causes questions or confusion.  The API documentation is not just the bet source, but the best practice you can perfect for a long term success. 

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;          //not covered until chapter 10
/**
 * This class summarizes all structures related to while loops including file IO with validation
 * @author Zoltan Szabo
 * @version 1.0.0
 */
public class WhileSummary
{
    /**
     * Entry point to application
     * @param args string array from the commandline sent to application
     * @return none
     */
public static void main(String[] args)throws Exception
{
      int value = 5;
  
      //File IO validation without try/catch block
      File inFile=new File("input.txt");   //source file name
      File outFile=new File("output.txt"); //destination file name
     
      if (!inFile.exists()){           //Checks if the file name exists
         System.out.println("Source file " + inFile + " does not exists.");
         System.exit(4);               // Exit the program.
      }
      Scanner input = new Scanner(inFile);  //Look at the Scanner constructor documentation to find what it throws when constructed with File parameter
          
      if (outFile.exists()){           //Checks if the file name already exists, look up the method docs
         System.out.println("The destination file " + outFile + " already exists.");
         System.exit(5);            // Exit the program. Look up the method docs
      }
      PrintWriter output = new PrintWriter(outFile);
     
      //while with counter control - if you know the number of iteration needed
      int counter=0;       //priming value
      while(counter < 5 ){                       //decision
          System.out.println("The value is: "+counter);
          counter++;                  //update                
      }
     
      //while with flag control - when the object controlling the loop has a property to test for
      while(input.hasNext()){                    //read input file until it reaches the end of file, method docs
          //System.out.println(input.nextLine());
          output.println(input.nextLine());           //Loop up the method docs
      }
     
      //while with sentinel control - when you want to allow user interaction or predefined value to end the iteration
      Scanner keyboard=new Scanner(System.in);
      char answer='y';                                             //priming value
      while(answer != 'n' ){                                       //decision
          System.out.println("Your answer is: "+answer);
          System.out.println("Enter it again (y/n): ");            //prompt
          String temp=keyboard.nextLine();                      
          answer = Character.toLowerCase(temp.charAt(0));          //update
      }
     
      //for loop - simplified while loop ternary format
      for(int count=0;counter < 5;count++ ){                       //priming value;decision;update
          System.out.println("The value is: "+count);
      }
      //continue / break usage in for loops
      for(int i=0;i<100;i++){
         if(i%2==0)
            continue;
         System.out.println(i);           //print only odd numbers
         if(i==55)
            break;                        //quit the loop at 55
      }
    
      //enhanced for loop
      //processing array the traditional way if index values need to be adjusted
      int array[]={1,2,3,4,5,6,7,8};
      for(int i=0;i<array.length;i+=2){
          System.out.println("The traditional way is: "+array[i]);
      }
      //if all values must be processed from start to finish
      for(int temp:array){
          System.out.println("The value is: "+temp*10);
      }
       
      //do while - when you want to have the loop run at least once - only post test loop
      answer='n';       //priming value
      do{
          System.out.println("Your answer is: "+answer);
          System.out.println("Enter it again (y/n): ");       //prompt
          String temp=keyboard.nextLine();                      
          answer = Character.toLowerCase(temp.charAt(0));     //update
      }while(answer != 'n' );                                 //decision
      //nested for loop - inter-dependent loops from fastest ( inner ) to slowest ( outer ) fastest loops
      //Simulate the clock.
      for (int hours = 0; hours <= 12; hours++)               //slowest loop
      {
          for (int minutes = 0; minutes <= 59; minutes++)     //slower loop
          {
             for (int seconds = 0; seconds <= 59; seconds++)  //fastest loop
             {
                System.out.printf("%02d:%02d:%02d", hours, minutes, seconds);
                System.out.printf((hours>=12)?"PM\r":"AM\r");
                Thread.sleep(1000);
             }
          }
      }
      //Deal with negative numbers in loops using private method and binary AND
      byte count=0;
      while(toUnsigned(count)>=0){
         System.out.println(toUnsigned(count));
         Thread.sleep(50);
         count++;
        }
     //System.out.println(count);
      input.close();         //Don't forget to close files
      output.close();
  }
 
private static int toUnsigned(byte n){
      return n&0x000000FF;
   }
}