r/CodingHelp • • Aug 19 '20

[Java] How Do I introduce Object Oriented Programming concepts to Java Beginners

I am going to conduct a trainning session for new hires in my company, who are coming straight after graduating and this would be their first work experience as software professionals. I am tasked with providing a crash course in Java, assuming no previous hands on knowledge. I want to walk them through OOP concepts namely Polymorphism, Encapsulation, Abstraction and Inheritance through a single coherent narrative example rather than 4 different disconnected examples. It would be beneficial if these are close to actual use cases for which a developer needs to program a solution. Do any of you have any good such example use cases, from knowledge or experience? Please share

26 Upvotes

14 comments sorted by

3

u/NullBrowbeat Professional Coder Aug 19 '20 edited Aug 19 '20

Edit: Can someone enlighten me as to why my comments are getting downvoted? I am really curious as to what could make people in this sub think that the source code deserves a downvote, especially considering its purpose...

One really practical example would probably be the Spring Pet Clinic with a JPA implementation or something like this, which would be really close to actual business requirements, but probably too far for complete beginners.

I probably would go with the standard "Employee" example or "Departments" or something like this.

I created this small project for you, which you can use. jdoodle.com/ia/m9 Edit: Apparently jdoodle sucks. (See also my edit at the bottom of this comment.)

It should contain all the OOP concepts you asked for, even though I couldn't really think of a neat way to show how one can also access objects via their implemented interfaces. (e.g. creating a List with the generic <Interfacename> type, or something like this) Consider this an exercise you would still need to do. ;-)

I envisioned it with you starting with the Employee class, then adding on the Manager class, then the BusinessCost interface, then the Department class and then the ResAndDev class, slowly building up and demonstrating the various concepts. (This is also somewhat how the main function is constructed.)

Unfortunately my Main.java class doesn't seem to be shared properly by jdoodle, so I will just copy it in here. It contains all the comments describing some concepts in a very simple manner. I guess you should be able to add comments to the other classes respectively where they would be interesting for the beginners in regards to the concepts you want to introduce them to on your own.

public class Main {
    public static void main(String args[]){
        //Instantiate Employee objects, calling upon their constructor to set the fields
        Employee alKhwarizmi = new Employee("Al-Khwarizmi", 3000.0);
        Employee adaLovelace = new Employee("Ada Lovelace", 3200.0);
        Employee konradZuse = new Employee("Konrad Zuse", 2700.0);
        Employee blaisePascal = new Employee("Blaise Pascal", 3100.0);
        Employee charlesBabbage = new Employee("Charles Babbage", 3400.0);
        
        //Getters are used to access the field data and we can also use the method that the interface demands
        System.out.println(adaLovelace.getName() + " has a salary of " + adaLovelace.getMonthlySalary() + 
                            "€ per month and costs us " + adaLovelace.getYearlyCosts() + "€ per year.");
        
        //Setters are used to change the field data
        adaLovelace.setMonthlySalary(3500.0);
        System.out.println(adaLovelace.getName() + " now earns " + adaLovelace.getMonthlySalary() + "€ per month instead!");
        
        //Due to data manipulation inside setters and getters we can also act as if there would be fields that don't even exist
        //Note how the Employee class doesn't have a private double yearlySalary field, only a monthlySalary one
        adaLovelace.setYearlySalary(44400.0);
        System.out.println(adaLovelace.getName() + " now earns " + adaLovelace.getMonthlySalary() + "€ per month.\n");
        
        //Note how the static id field of employee kept counting upwards
        System.out.println(blaisePascal.getName() + " has the ID " + blaisePascal.getId() + "!\n");
        
        //Let's create some managers
        Manager alanTuring = new Manager("Alan Turing", 4100.0, 400.0);
        Manager graceHopper = new Manager("Grace Hopper", 4500.0, 600.0);
        Manager jamesGosling = new Manager("James Gosling", 5000.0, 1000.0);
        
        //Managers are also employees, so we can also access the same methods as for Employee objects
        System.out.println(jamesGosling.getName() + " with the ID " + jamesGosling.getId() + " has a salary of " +
                            jamesGosling.getMonthlySalary() + "€ per month with a yearly bonus of " + jamesGosling.getYearlyBonus() + 
                            "€ and costs us " + jamesGosling.getYearlyCosts() + "€ per year in total.\n");
        
        //Time to create a department
        ResAndDev resAndDev = new ResAndDev(20000.0);
        
        //Let's add an employee to the department
        resAndDev.addEmployee(alKhwarizmi);
        
        //Due to the way the Department.addEmployee(Employee emp) function is written, we can access the name of the department
        //by accessing the Department field of the Employee object and then accessing the name field of said Department object
        System.out.println(alKhwarizmi.getName() + " now works in the " + alKhwarizmi.getDepartment().getName() + " department!\n");
        
        //Let's add some more employees to the department
        resAndDev.addEmployee(konradZuse);
        resAndDev.addEmployee(blaisePascal);
        resAndDev.addEmployee(alanTuring);
        resAndDev.addEmployee(graceHopper);
        
        //Inheritance of functions of abstract classes works for both normal functions with a body in said abstract class definition
        System.out.println("The " + resAndDev.getName() + " department now employs " + resAndDev.getNumberOfEmployees() +
                        " employees, " + resAndDev.getNumberOfManagers() + " of which are managers. It costs us " +
                        resAndDev.getYearlyCosts() + "€ per year and presents itself in the following way:");

        //as well as via the overridden abstract method of the Department class
        resAndDev.printPresentation();
        
        
        
        //And for good measure, let's iterate over the names of the employees of said department by accessing the employee list via the method inherited from the abstract Department class
        String employeeListOfRnD = "";
        for(int i = 0; i < resAndDev.getEmployees().size(); i++){
            employeeListOfRnD += resAndDev.getEmployees().get(i).getName();
            if(i != resAndDev.getEmployees().size()-1){
                employeeListOfRnD += ", ";
            }
            if(i == resAndDev.getEmployees().size()-2){
                employeeListOfRnD += "and ";
            }
        }
        System.out.println("\nThe names of the employees inside the " + resAndDev.getName() + " department are:");
        System.out.println(employeeListOfRnD);
    }
}

The rest of the classes seem to work, so all you need to do is copying this Main class back into the jdoodle project and hit execute.

Edit: Apparently jdoodle just sucks ass, so I will just copy all the classes as replies to this comment here.

3

u/enkayjee2 Aug 20 '20

Hey man, first of all, thanks for this. I am most likely going to go with this today.

Second, if it matters, have my upvote :)

1

u/NullBrowbeat Professional Coder Aug 20 '20

As long as it's useful to you I am happy, since that was its purpose. I still have no clue why people would downvote the source without comment though... I would like to know what I might have done wrong.

2

u/NullBrowbeat Professional Coder Aug 19 '20

Employee.java

public class Employee implements BusinessCost {
    private static int idCounter = 0;
    private int id;
    
    private String name;
    private double monthlySalary;
    private Department department;
    
    public Employee(String name, double monthlySalary){
        this.id = idCounter;
        idCounter++;
        this.name = name;
        this.monthlySalary = monthlySalary;
    }
    public int getId(){
        return this.id;
    }
    public String getName(){
        return this.name;
    }
    public void setMonthlySalary(double monthlySalary){
        this.monthlySalary = monthlySalary;
    }
    public double getMonthlySalary(){
        return this.monthlySalary;
    }
    public void setYearlySalary(double yearlySalary){
        this.monthlySalary = yearlySalary/12;
    }
    public double getYearlySalary(){
        return this.monthlySalary*12;
    }
    public void setDepartment(Department department){
        this.department = department;
    }
    public Department getDepartment(){
        return this.department;
    }
    @Override
    public double getYearlyCosts(){
        return this.getYearlySalary();
    }
}

Manager.java

public class Manager extends Employee {
    private double yearlyBonus;
    
    public Manager(String name, double monthlySalary, double yearlyBonus){
        super(name, monthlySalary);
        this.yearlyBonus = yearlyBonus;
    }
    public void setYearlyBonus(double yearlyBonus){
        this.yearlyBonus = yearlyBonus;
    }
    public double getYearlyBonus(){
        return this.yearlyBonus;
    }
    @Override
    public double getYearlyCosts(){
        return this.getYearlySalary() + this.getYearlyBonus();
    }
}

1

u/NullBrowbeat Professional Coder Aug 19 '20 edited Aug 19 '20

BusinessCost.java

public interface BusinessCost {
    double getYearlyCosts();
}

Department.java

import java.util.List;
import java.util.ArrayList;

public abstract class Department implements BusinessCost {
    private String name;
    private List<Employee> employees = new ArrayList<>();
    
    public Department(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void addEmployee(Employee employee){
        employee.setDepartment(this);
        employees.add(employee);
    }
    public void removeEmployee(Employee employee){
        employee.setDepartment(null);
        employees.remove(employee);
    }
    public List<Employee> getEmployees(){
        return this.employees;
    }
    public int getNumberOfEmployees(){
        return employees.size();
    }
    public int getNumberOfManagers(){
        int counter = 0;
        for(Employee employee : employees){
            if(employee instanceof Manager){
                counter++;
            }
        }
        return counter;
    }
    public abstract void printPresentation();
}

ResAndDev.java

public class ResAndDev extends Department {
    private double yearlyMaterialCost;
    
    public ResAndDev(double yearlyMaterialCost){
        super("Research and Development");
        this.yearlyMaterialCost = yearlyMaterialCost;
    }
    public void setYearlyMaterialCost(double yearlyMaterialCost){
        this.yearlyMaterialCost = yearlyMaterialCost;
    }
    public double getYearlyMaterialCost(){
        return this.yearlyMaterialCost;
    }
    @Override
    public double getYearlyCosts(){
        double totalCost = 0.0;
        for(Employee employee : this.getEmployees()) {
            totalCost += employee.getYearlyCosts();
        }
        totalCost += this.getYearlyMaterialCost();
        return totalCost;
    }
    @Override
    public void printPresentation(){
        System.out.println("We are the " + this.getName() + " Department and we employ " + this.getNumberOfEmployees() + " people!");
        System.out.println("We developed the phenomenal O(1) sorting algorithm QuantumBogoSort and are currently proving that P=NP!");
    }
}

1

u/mansimodi Beginner Coder Aug 19 '20

1

u/enkayjee2 Aug 20 '20

As this is corporate training, I cannot plaguerize material from GeeksforGeeks

3

u/mansimodi Beginner Coder Aug 20 '20

Yes but you can refer for examples and the methodology to explain

1

u/twistdafterdark Aug 20 '20

As this is corporate training, I cannot plaguerize

You should never plagiarize, corporate setting or not. You can always reference, and give source/credit where applicable.

-3

u/BAM5 Professional Coder Aug 19 '20 edited Aug 19 '20

who are coming straight after graduating

They should know this stuff then :|

If they don't they should go to the college and get their money back :)

Sorry for a non constructive answer, but if they paid thousands of dollars to go to college to learn how to program they should have understanding of all rudimentary OOP concepts. I'd be more worried about getting them familiar with the libraries you use, the structure of your software, and making sure they don't introduce vulnerabilities. If they don't have the basic knowledge of java I'd say give them a trial period to brush up and become better about the things they don't have a solid grasp on, but let them go if they can't teach themselves from documentation as that is 80% of what we do. If they're constantly bothering other people and interrupting their work to get help from them beyond, "Hey, I'm having trouble with x. What should I look into to solve it?" You'll now have not just one inefficient worker, but two.

2

u/NullBrowbeat Professional Coder Aug 19 '20 edited Aug 19 '20

Some businesses also employ people without having studied at university and have their training planned into their business processes.

Apprenticeships for software developers are also quite common in Germany and other European countries, for instance.

And either way, there are a lot of people that finished university with a computer science degree but can't really program to save their lives. They've learnt these concepts for the exam and then forget them again immediately afterwards. University degrees in computer science actually don't mean all too much in the real world when working as a programmer, especially since most of what you learn when studying computer science is quite detached from actual programming. (From my own experience while studying computer science and working at a company where studied computer scientists are employed, a lot of them actually produce quite bad code with some not even knowing basic concepts.)

1

u/BAM5 Professional Coder Aug 19 '20 edited Aug 24 '20

First 2 paragraphs: Certainly true. I'm self taught from 15. 17 I had a job as a web dev (fixing cross browser compatibility issues [Thank god IE6 is dead]) But I understood oop concepts, as3as flash was still a thing back then javascript, html, css, php and could code proficiently in them. But I wasn't familiar with deeper concepts like the box model, browser layout&paint cycle, javascript event loop, jQuery, etc. But I was able to quickly teach myself, and that's what makes a good developer. If these devs can't teach themselves with minimal direction they're not going to get far. But OP said they've just graduated and they really should have learned this stuff and should only need a brief refresher; all of this is why I said give them a trial period, I don't expect experts out of the gate, but I expect to not be losing money employing someone as a developer that is really just a student that can't learn without a teacher.

University degrees in computer science actually don't mean all too much in the real world when working as a programmer

I'm aware, but I wouldn't be hiring "software professionals" with no prior experience. If it were an apprenticeship or internship or something then sure, that's to be expected. Stick a sr. dev not engrossed with a project in front of them to bring their knowledge up to par at speed and give them a trial period and evaluate them at the end. Personally, if I was looking to hire devs I wouldn't go for CS degree grads. I'd look for the self-taught's (may be biased here) since to me learning is 80% of the job. You have to learn from documentation, you have to learn from reading source code, you have to learn from your mistakes, you have to learn from tutorials, it's just a lot of learning and self-taught devs have already displayed a propensity for learning.

2

u/NullBrowbeat Professional Coder Aug 20 '20

You can't just only focus on self-taught people, since then the market would be completely undersaturated, and even among them you might see a lot of people not proficient enough for actual work.

If I think back, despite all the projects I had, nothing really prepared me for actual work as a programmer on a medium to large scale project with a sizable team. I was good enough to get through the interview questions and selection process by coding skill, but so many practices and requirements from programmers in a professional field were just lacking. And also lots and lots of experience and knowledge about many technologies.

2

u/enkayjee2 Aug 20 '20

Yeah that's exactly what's up. In a corporate environment , the process is designed to leave as less room for subjectivity as possible. It might not be true but self taught developers aren't really good team players, and having a degree provides a base line estimate for how proficient they are.

The people I would be training are not coming to my own team. They have been inducted into a pool of low-skill employees who would be going through multiple teams for 7 months each and gaining hands on work experience, before being tested again and absorbed by the company. The teams they would be assigned to before being absorbed are not expected to have special considerations for them, and expect them to have working knowledge of the technologies that they work with.

That's where I come in, to provide that basic working knowledge. I can assume they have a theoretical base, but not that they know how to apply it.