简体   繁体   中英

Creating a superclass and subclass with constructors - Java

I am new to Java. I have a problem to solve, but I don't quite understand how constructors work. I understand how to create a superclass and a subclass but I don't understand the constuctors within them (or how they actually work - I have done rediculous amounts of research on constructors, but it's just not making much sense).

I am trying to write a program that creates a superclass called Employees. This Employee class has instance variables employeeId (which is an integer) and employeeName (which is a String).

The subclass is called Manager. The Manager subclass has an instance variable called employeeTitle (which is a String). It also has a method with the name of managerDetails(). ManagerDetails() is supposed to display the employeeId, employeeName, and the employeeTitle.

This is what I have so far:

package tryingoutjava;

public class TryingOutJava {

    class Employee {

        int employeeId;
        String employeeName;

        void Employee() {

        }
    }

    class Manager extends Employee {

        String employeeTitle;

        void managerDetails() {

        }
    }

    public static void main(String[] args) {

    }
}

I am very confused on how to set up the constructors for the superclass and the subclass, or even what a constructor really looks like. I've seen examples all over the internet, but no one actually highlights the actual part that is the constructor, or how everything is linked visually, which is what helps me learn.

I guess I'm also having issues with understanding how to set up a method that calls on an object. If anyone has the time to help, it would greatly be appreciated. Thanks!

I guess you want something like this. Be noted, that it is a good idea to separate classes one-per-file in this case, as they are separate entities here. It is a good idea to limit data access to entity fields, as such using encapsulation.

Employee.java:

package tryingoutjava;

public class Employee {

    // Protected access because we want it in Manager
    protected int employeeId;
    protected String employeeName;

    public Employee(int employeeId, String employeeName) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
    }
}

Manager.java:

package tryingoutjava;

public class Manager extends Employee {

    private String employeeTitle;

    public Manager(String employeeTitle, int employeeId, String employeeName) {
        // Use super to invoke Employee constructor
        super(employeeId, employeeName);
        this.employeeTitle = employeeTitle;
    }

    // Just create a simple string describing manager
    @Override
    public String toString() {
        return "Manager{" +
                "employeeTitle='" + employeeTitle +
                "employeeId=" + employeeId +
                ", employeeName='" + employeeName + '\'' +
                '}';
    }
}

Application.java:

package tryingoutjava;

public class Application {

    // Example of construction plus printing of Manager data
    public static void main(String[] args) {
        Employee davie = new Employee(1, "Dave The Cable Guy");
        Manager tom = new Manager("CFO", 2, "Tomas");
        System.out.println(tom.toString());
    }
}

Constructors (most often than not) just delegate construction of parent through super invocation. While there are other techniques, like Builder pattern, this is the most basic and understandable approach. There are several other ways to do this, but this should get you started, hope it helps!

Purpose of Constructor

constructor is a method like other method but it is called when instantiate (or create a object from your class) for initialize your object for first use or later use. for example a class like Student must created (instantiated) when we give it name and family name for example. Without them, create a Student is not good because maybe we forget to give it proper name and use it incorrectly. constructor forces us to provide minimum things needed for instantiating objects from classes.

Constructor implementation in inheritance

About inheritance, it is different. When you want to create a Student which is a Human ( extends Human ) you must first create Human inside your Student and set special feature for your Student like ID which is not for Human ( Human has name and etc). so when you create a Student with constructor, the super constructor (for Human ) is called too.

What do we do in constructor

as I mentioned, we provide default value for our properties which must set them before creating and using object. (for using them properly) every subclass call super class constructor implicitly with super() but if super class doesn't have any default constructor (constructor with no argument) you must explicitly say super(...) at the first lien of subclass constructor (otherwise compile error)

What is the program steps when using constructor (Advanced)

  1. super class static constructor and static variable (read by self if you want to know more about things I say here)
  2. subclass class static constructor and static variable
  3. super class variable and block constructor
  4. super class constructors
  5. sub class variable and block constructor
  6. sub class constructors

I only mentioned 4 & 6. I try to explain completely. My English is not good. I'm sorry.

If you know how a method works, then you know how a constructor works. The constructor is simply a special method that allows you to execute some code before the object is created.

Person p = new Person("Bob", 25); // Calls constructor Person(String name, int age)

Then in the constructor you can do things like assign initial values to any instance variables.

private String name;
private int age;

public Person(String name, int age) {
    this.name = name;
    this.age = age;
}

If the class is a subclass you need to call a constructor of the parent class before the object is created unless the parent class has a constructor with no parameter in which case java can call it for you if you don't specify anything. Here Worker extends Person.

private String occupation;

public Worker(String name, int age, String occupation) {
    super(name, age) // Calls constructor Person(String name, int age)
    this.occupation = occupation;
}

I guess you can achieve what you want in a single file via the code snippet below: You can copy paste it in your code and it should work.

You can see how the constructor of parent class is being called by the help of super() and also the methods. Here I have used methods like getEmployeeTitle() which should help you get an overview on how to write methods. I have also overridden the toString() method so that you can understand how to override Object class' useful methods like toString().

Note : Although I have created all the classes in one code snippet for the sake of simplicity , but it is highly recommended that you create a separate file for each of these classes.

class Employee {

    int employeeId;
    String employeeName;

    Employee(int employeeId, String employeeName) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
    }

}

class Manager extends Employee {

    private String employeeTitle;

    Manager(int employeeId, String employeeName, String employeeTitle) {
        super(employeeId, employeeName);
        this.employeeTitle = employeeTitle;
    }

    public String getEmployeeTitle() {
        return employeeTitle;
    }

    @Override
    public String toString() {
        return ("employeeId: " + employeeId + ", employeeName: " + employeeName + ", employeeTitle" + employeeTitle);
    }
}

public class TryingOutJava {
    public static void main(String[] args) {
        Manager manager = new Manager(007, "John Doe", " Sr. Manager");
        System.out.println(manager);
        System.out.println(manager.getEmployeeTitle());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM