Search code examples
javapolymorphism

Using Java inheritance for getting value from its parent


Should I use extends keyword to get value of variable from its parent. Is that appropriate? I have here a code:

package salarypackageoop;

import java.util.Scanner;

public class mainFunction {

    Scanner input = new Scanner(System.in);
    double totalOvertime;
    double totalHours;
    double totalTardiness;

    public void timeIn() {

        String dayOfwork[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
        double getNum = 0;
        System.out.println("------------ TIME IN ------------");

        for (int i = 0; i < dayOfwork.length; i++) {

            System.out.println(dayOfwork[i] + ": ");
            getNum = input.nextDouble();

            totalHours += getNum;

            if (getNum < 8) {

                System.out.println("No overtime today!");
                totalTardiness += 8 - getNum;

            } else if (getNum == 8) {

                isValid();

            }
        }

        System.out.println("PAY per hour: 200.50");
        System.out.println("---------------------");
        System.out.println("Overtime rate: 75.25");
        System.out.println("Overtime: " + totalOvertime);
        System.out.println("Number of hours: " + totalHours);
        System.out.println("-----------------------");

    }

    public void isValid() {

        System.out.println("You can do overtime work if you want!");
        System.out.print("How many hours? ");
        int getHours = input.nextInt();

        totalOvertime += getHours;
    }

}

class function2 extends mainFunction {

    void display(String name, String id) {
        
        System.out.println("SALARY INFORMATION");
        System.out.println("-----------------------");
        System.out.println("Employee Id       : " + name);
        System.out.println("Employee Name     : " + id);
        System.out.println("Number of hours   : " +super.totalHours);
        System.out.println("Employee Tardiness: " +super.totalTardiness);
        System.out.println("-----------------------");
    }

}

I used super keyword to get the value of totalHours and totalTardiness from its parent but whenever I run the program, totalHours and totalTardiness has no value.

and here's my main method where I call classes and its methods:

package salarypackageoop;

import java.util.Scanner;
public class SalaryPay {

    public static void main(String[] args) {

        String getName;
        String getId;
        Scanner input = new Scanner(System.in);
        System.out.println("Calculate Employee salary Per Week");
        System.out.println("Input Employee's Data First...");
        
        System.out.print("Employee Name: ");
        getName = input.nextLine();
        System.out.print("Employee Id: ");
        getId = input.nextLine();
        
            employeeData setData = new employeeData();
            setData.setEmployeeData(getName, getId);
            getName = setData.getEmployeeName();
            getId = setData.getEmployeeId();
            
            mainFunction callMeth = new mainFunction();
            callMeth.timeIn();

            function2 callMeth2 = new function2();
            callMeth2.display(getName, getId);
    }
    
}

My output goes like this:

Calculate Employee salary Per Week
Input Employee's Data First...
Employee Name: sambajon
Employee Id: emp-212
------------ TIME IN ------------
Monday: 
8
You can do overtime work if you want!
How many hours? 2
Tuesday: 
8
You can do overtime work if you want!
How many hours? 2
Wednesday: 
7
No overtime today!
Thursday: 
7
No overtime today!
Friday: 
7
No overtime today!
PAY per hour: 200.50
---------------------
Overtime rate: 75.25
Overtime: 4.0
Number of hours: 37.0
-----------------------
SALARY INFORMATION
-----------------------
Employee Id       : sambajon
Employee Name     : emp-212
Number of hours   : 0.0
Employee Tardiness: 0.0
-----------------------

Solution

  • You appear to be creating new objects, and expecting them to be filled in, or to share data. For example:

    mainFunction callMeth = new mainFunction();
    callMeth.timeIn();
    
    function2 callMeth2 = new function2();
    callMeth2.display(getName, getId);
    

    Here, you create a new instance of the mainFunction class, named callMeth. Then you call the timeIn() method of that object.

    Next, you create a new instance of the function2 class, named callMeth2. What you must realize is that callMeth and callMeth2 are completely independent objects, each with their own members and field values.

    Seeing as callMeth2 is a completely independent object, nothing has actually been done to it to set the variables you wish to display.

    Perhaps you could try the following:

    function2 callMeth2 = new function2();
    
    // Initialize the data fields of object callMeth2
    callMeth2.timeIn();
    
    // Display callMeth2
    callMeth2.display(getName, getId);
    

    This will perform all the operations on the same object, and so the display function will have properly initialized fields to print out.

    Let's see if I can add an analogy.

    enum GENDER { male, female, noneoftheabove, etc };
    class Human
    {
        String name;
        GENDER gender;
        public String getName() { return name; }
        public void setName(String nm) { this.name = nm; }
    }
    

    Here we have a Human class, and objects of the human class have a name and a gender.

    class Wizard extends Human
    {
        boolean parselmouth;
        public String getNameAndGender() { return name + gender; }
    }
    

    Wizard class extends from Human, because they all have a name and gender, but they also might be a parselmouth.

    To use these classes, you need to create an object of the type you want. For example,

    Human dudley = new Human();
    dudley.setName("Dudley Dursley");
    
    Wizard harry = new Wizard();
    harry.setName("Harry Potter");
    harry.parselmouth = true;
    

    What you are doing is akin to the following:

     // Create a Human
     Human h = new Human();
     h.setName("Dudley Dursley");
     h.gender = GENDER.male;
    
     // Create a Wizard
     Wizard wiz = new Wizard();
     // wiz is not initialized in any way
    
     // Print out the name and gender of wiz:
     System.out.println(wiz.getNameAndGender());
    

    and expecting the output to be "Dudley Dursley male".