Java 2

Week 1

Topics

  • UML Class Diagrams
  • Classes and Objects
  • Collections (List and ArrayList)
  • GitHub Setup

What is UML?

  • UML is the “Unified Modeling Language”
  • Standard modeling language for software development
  • Maintained by Object Management Group
  • Made up of pseudo-code, notations, pictures, diagrams, etc
  • Describes the system we want to develop

UML Textbook

Class Diagrams

  • Class diagrams show the classes of the system, their relationships, and the attributes and operations (methods).

  • Classes form the main building blocks of an object-oriented application.

User
- userId : int
- firstName : String
- lastName : String
+ getUserId() : int
+ setUserId(int) : void
+ getFirstName() : String
+ setFirstName(String) : void
+ getLastName() : String
+ setLastName(String) : void
+ toString() : String

Three Boxes

  • Classes are depicted as boxes with three sections:
    • The top box indicates the name of the class. The name is typically a singular noun. Class names should always start with a capital letter.
    • The middle box lists the attributes of the class - the information stored about an object
    • The bottom box lists the methods - the operations an object or class do.
Name
- attributes
+ methods

Access Modifiers

  • The + symbol represents a public access modifier, meaning all other classes have access.
  • The - symbol represents a private access modifier, meaning only the current class has access.
  • The / symbol (not shown) represents a derived modifier - a value not stored but is calculated from other attributes when needed
    • ​For example, GPA could be derived from a list of grades
  • The # symbol (not shown) represents a protected access modifier, meaning other classes in the same package has access to the attribute.
User
- userId : int
- firstName : String
- lastName : String
+ getUserId() : int
+ setUserId(int) : void
+ getFirstName() : String
+ setFirstName(String) : void
+ getLastName() : String
+ setLastName(String) : void
+ toString() : String

Data Types, Parameters, Return

  • Attribute data types are shown after a colon.
  • Method parameters are shown inside parentheses.
    • ​Getter methods and the toString method have no parameters.
    • Setter method parameters will typically match the attribute data type.
  • Method return types are shown after the colon.
    • Getter methods will always return the attribute data type.
    • Setter methods will always return void.
    • The toString method will always return a String.
User
- userId : int
- firstName : String
- lastName : String
+ getUserId() : int
+ setUserId(int) : void
+ getFirstName() : String
+ setFirstName(String) : void
+ getLastName() : String
+ setLastName(String) : void
+ toString() : String

Inheritance

  • Inheritance is a mechanism to prevent writing repeated code.
  • Inheritance models “is a” relationships, enabling you to reuse existing attributes and methods easily.
  • When A inherits from B, we say A is the subclass of B, and B is the superclass of A.
  • The notation for inheritance is a line with an open arrowhead pointing from the subclass to the superclass.
Professor
- salary : double
+ getSalary(): double
+ setSalary(double): void
+ toString(): String
Student
- gradeLevel : int
- gpa : double
+ getGradeLevel(): int
+ setGradeLevel(int): void
+ getGpa(): int
+ setGpa(int): void
+ toString(): String
User
- userId : int
- firstName : String
- lastName : String
+ getUserId : int
+ setUserId : void
+ getFirstName : String
+ setFirstName : void
+ getLastName : String
+ setLastName : void
+ toString : String

is a

is a

Associations

  • Objects are often associated with other objects.

  • For example:

    • A professor instructs a course

    • A student enrolls in a course

    • A course has enrollments

  • Associations are modeled as lines connecting the two classes.

  • Associations can be clarified by depicting labels and directionality.

Enrollment
- student : Student
- course : Course
- finalGrade : char
+ getStudent(): Student
+ setStudent(Student): void
+ getSection(): Section
+ setSection(Section): void
+ getFinalGrade(): char
+ setFinalGrade(char): void
+ toString()
Course
- courseId : int
- title: String
- featured: boolean
+ getCourseId(): int
+ setCourseId(int): void
+ getTitle(): String
+ setTitle(String): void
+ isFeatured(): boolean
+ setFeatured(boolean): void
+ toString(): String

instructs

has

has

Professor
Student
User

Composition Associations

  • If it makes sense to say something is part of (or consists of) something else, then you should use composition (aka aggregation).
  • Composite associations are shown with a diamond.
  • For example, it makes sense to say that:
    • Enrollment is on a grade report -or- a grade report is composed of enrollments.
    • A room is part of a building -or- a building is composed of rooms.
Enrollment
Student
GradeReport
- student : Student
- enrollments : List<Enrollment>
- dateCreated : LocalDate
// methods omitted

receives

composed of

has

Association Multiplicity

  • The multiplicity of the association is labeled on either end of the line, one multiplicity indicator for each direction

  • Each student has 0 or more enrollments.

    • Each enrollment has 1 student.

  • Each professor instructs 0 to 5 courses.

    • Each course has 1 to 3 professors.

Indicator Meaning
0..1 Zero or one
0..* Zero or more
0..n (such as 0..10) Zero to n (such as zero to ten)
n (such as 1) Exactly n (Only one)
1..* One or more
1..n (such as 1..10) One to n (such as one to ten)
Enrollment
Course
Professor
Student
User

1

0..*

0..6

1..3

1

0..*

  • Each course has 0 or more enrollments.

  • Each enrollment has 1 course.

UML Diagramming Tools

Week 1 Lab

Your Task:

Week 1 Assignment

  • An administrator updates the product catalog. Each product has a product id, vendor id, name, price, and description.
  • Each product may be purchased from one or more vendors. Each vendor has an id, name, and address (city, state, zip, country).
  • A customer can place an order by submitting a form. The order form collects the customer's name, address  (city, state, zip, country), phone number, and email address.
  • Each order has an id, date, and customer id. An order consists of one or more order items.
  • Each order item is associated with an order and a product. It also contains the quantity sold and price.

Your Task:

  • Identify six nouns from the problem domain above that can be used as classes.

  • Use a diagramming tool to create a class diagram with access modifiers, data types, parameters, return types, inheritance, associations, composition, multiplicity, and annotations.

New Java Project

  • Create a new Java Maven project using VS Code. Call the project "java2-demos". Use "edu.kirkwood" as the groupId.
    • Companies often declare packages starting with their website domain written backwards.
    • We will use VS Code to prepare you for a state Java programming competition in Des Moines next February.
    • We will eventually use JetBrains IntelliJ to build a web application using the code we are writing today. 
  • In the root folder, create a .gitignore file. Add this to ignore compiled class files
    *.class
  • Inside the "edu.kirkwood" package, create a new package called "learnx".
  • Inside the "learnx" package, create a new package called "model", "controller", and "data". We will create a "view" package later.

LearnxUser Class

  • In the model package, create the User class with these attributes.
    • userId : int
    • firstName : String
    • lastName : String
  • Generate default and parameterized constructors, getter and setter methods, and a toString method.
package edu.kirkwood.learnx.model;

public class LearnxUser {
    private int userId;
    private String firstName;
    private String lastName;
    
    public LearnxUser() {}

    public LearnxUser(int userId, String firstName, String lastName) {
        this.userId = userId;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "LearnxUser [userId=" + userId + ", firstName=" + firstName + ", lastName="
                + lastName + "]";
    }

}

Student Class

  • In the model package, create the Student class that inherits User, with these attributes.
    • gradeLevel : int
    • gpa : double
  • Generate default and parameterized constructors, getter and setter methods, and a toString method.
package edu.kirkwood.learnx.model;

public class Student extends LearnxUser {
    private int gradeLevel;
    private double gpa;

    public Student() {
        super();
    }

    public Student(int userId, String firstName, String lastName, int gradeLevel, double gpa) {
        super(userId, firstName, lastName);
        this.gradeLevel = gradeLevel;
        this.gpa = gpa;
    }

    public int getGradeLevel() {
        return gradeLevel;
    }

    public void setGradeLevel(int gradeLevel) {
        this.gradeLevel = gradeLevel;
    }

    public double getGpa() {
        return gpa;
    }

    public void setGpa(double gpa) {
        this.gpa = gpa;
    }

    @Override
    public String toString() {
    	return "Student [userId=" + getUserId() + ", firstName=" + getFirstName() + ", lastName="
                + getLastName() + ", gradeLevel=" + gradeLevel + ", gpa=" + gpa + "]";
    }

    

    
}

StudentDAO Class

  • In the data package, Create a StudentDAO (data access object) class that will be used to create Student objects.
  • Create a method called getSampleStudents that returns a List of two Students.
package edu.kirkwood.learnx.data;

import java.util.ArrayList;
import java.util.List;
import edu.kirkwood.learnx.model.Student;

public class StudentDAO {
    public static List<Student> getSampleStudents() {
        List<Student> students = new ArrayList<>();
        students.add(new Student());
        students.add(new Student(1, "Marc", "Hauschildt", 12, 3.65));
        return students;
    }
}

SeatingChartBuilder Class

  • In the controller package, create a SeatingChartBuilder class with a main method that calls the getSampleStudents method and prints the two Student objects.
package edu.kirkwood.learnx;

import java.util.List;
import edu.kirkwood.learnx.data.StudentDAO;
import edu.kirkwood.learnx.model.Student;

public class SeatingChartBuilder {
    public static void main(String[] args) {
        List<Student> students = StudentDAO.getSampleStudents();
        for(Student student: students) {
            System.out.println(student);
        }
    }
}

Git Setup

  • Open the "java2-demos" folder in VS Code. Make sure the "src", folder is visible.
  • Click the "Terminal" menu and select "New Terminal". Click the arrow next to the "+" button. Choose "Select Default Profile". Select Git Bash. Click the trash can icon to close the terminal.
  • Click the "Source Control" button on the left taskbar.
  • Click the blue "Initialize Repository" button.
    • Alternatively, open a new Terminal and enter this command:
      git init -b main
    • If the task bar at the bottom-left displays "master" instead of "main", run this command:
      git checkout -b main

Git Setup

  • The panel will indicate that there are several uncommitted changes. Hold your mouse over the word "Changes" to see 3 new buttons "View Changes", "Discard All Changes", and "Stage All Changes". Click "Stage All Changes".
    • Alternatively, enter this command in the terminal.
      git add .
    • Note that you can also add files individually.
  • Type the message "initial commit" and press the blue "Commit" button.
    • Make sure you have added your name and email with these terminal commands.
      git config --global user.name "YOUR FULL NAME"
      git config --global user.email "YOUR EMAIL ADDRESS"
    • Alternatively, enter this command
      git commit -m "initial commit"

Git Setup

  • Click the blue "Publish Branch" button.
  • The first time you do this you will need to sign into GitHub.
    • Windows Users: Sign in with your GitHub password.
    • Mac Users: When signing in with your GitHub password, you may get an error saying you need to use a personal access token. See the next slide for instructions.
  • Click "Publish to GitHub private repository".
  • Alternatively, manually create a private "java2-demos" repository, then enter these commands in the terminal:
    git remote add origin https://github.com/YOUR-USERNAME/java2-demos.git

    git push origin main

**Mac Users**

  • Click "Log In with Token".
  • Click "Generate".
  • Log in to your GitHub account.
  • You will be on a screen to generate a new personal access token. The note should be pre-filled with "IntelliJ IDEA GitHub integration plugin".
  • Set the expiration date to be after the semester ends (or Never).
  • Select the Repo check box.
  • Click Generate Token and copy the token that is generated.
  • Paste the token as the password in the IntelliJ GitHub popup.
  • In the Terminal app, enter this command so you only have to enter the token once.
    git config --global credential.helper cache

Git Setup

  • View your GitHub repository page to see the changes.
  • As we advance, commit regularly. Please change commit messages each time to something short and descriptive. Only push to GitHub when your work is ready to grade.
  • Student To-do:
    • Click the "Settings" tab.
    • Choose Access > Collaborators, and click "Add people".
    • Type "mlhaus" and select the instructor's profile. The instructor will grade all assignments via GitHub. 
  • Instructor To-do:
    • Click the "Settings" tab, then set the visibility to public so students can access it.
    • Copy and paste a link to the course content so students always have access to demo code.

 

Git Setup

  • Note the tab in the menu bar displays "main". If it does not, initialize your project with Git. Open the Terminal tab and enter this command:
    git init -b main
  • If the menu bar displays "master", run this command:
    git checkout -b main
  • Note that files in the project panel may be red. This red text does not mean the file has an error. It means that the file is uncommitted with Git.
  • Open .gitignore and add this line.
    .env
  • Create a .env file in the src/main/resources folder. Add this line to the file:
    # Key=Value

Git Setup

  • Click the Git menu and select Commit. 
  • Select the files that you want to commit, including Unversioned Files. Note that the .env file should not be listed.
  • Uncheck the "Analyze Code" and "Check TODO" boxes.
  • Write a commit message. The message should be a short description of what you recently accomplished.
    Initial commit
  • Click "Commit". Don't click "Commit and Push".
  • If a "Line Separators Warning" message displays, check the "Don't warn again" box and click "Fix and Commit".
  • Note that the files are no longer red in the project panel.

GitHub Setup

  • Create a new private repository on GitHub. Title the repository "java-demos". Copy the URL.
  • Enter this command in the terminal:
    git remote add origin https://github.com/YOUR-USERNAME/java-demos.git
  • Click the Git menu and select "Push".
  • Verify that your main branch is being pushed to the origin's (GitHub's) main branch. Verify the files that are being pushed.
  • The first time you do this you will need to sign into GitHub
    • Windows Users: Sign in with your GitHub password.
    • Mac Users: When signing in with your GitHub password, you may get an error saying you need to use a personal access token. See the next slide for instructions.

**Mac Users**

  • Click "Log In with Token".
  • Click "Generate".
  • Log in to your GitHub account.
  • You will be on a screen to generate a new personal access token. The note should be pre-filled with "IntelliJ IDEA GitHub integration plugin".
  • Set the expiration date to be after the semester ends (or Never).
  • Select the Repo check box.
  • Click Generate Token and copy the token that is generated.
  • Paste the token as the password in the IntelliJ GitHub popup.
  • In the Terminal app, enter this command so you only have to enter the token once.
    git config --global credential.helper cache

GitHub Setup

  • Refresh your GitHub repository page to see the changes.
  • As we advance, commit regularly. Please change commit messages each time to something short and descriptive. Only push to GitHub when your work is ready to grade.
  • Student To-do:
    • Click the "Settings" tab
    • Choose Access > Collaborators, and click "Add people".
    • Type "mlhaus" and select the instructor's profile. The instructor will grade all assignments via GitHub.
  • Instructor To-do:
    • Click the "Settings" tab, then set the visibility to public so students can access it.
    • Copy and paste a link to the course content so students always have access to demo code.
 

Java 2 - Week 1

By Marc Hauschildt

Java 2 - Week 1

  • 266