简体   繁体   English

使用构造函数创建超类和子类-Java

[英]Creating a superclass and subclass with constructors - Java

I am new to Java. 我是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. 我正在尝试编写一个程序,该程序创建一个称为Employees的超类。 This Employee class has instance variables employeeId (which is an integer) and employeeName (which is a String). 该Employee类具有实例变量employeeId(它是一个整数)和employeeName(它是一个字符串)。

The subclass is called Manager. 子类称为管理器。 The Manager subclass has an instance variable called employeeTitle (which is a String). Manager子类具有一个名为employeeTitle(它是一个字符串)的实例变量。 It also has a method with the name of managerDetails(). 它还有一个名为managerDetails()的方法。 ManagerDetails() is supposed to display the employeeId, employeeName, and the employeeTitle. ManagerDetails()应该显示employeeId,employeeName和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: 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: 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: 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. 构造函数(大多数情况下)只是通过super调用来委托父结构。 While there are other techniques, like Builder pattern, this is the most basic and understandable approach. 尽管还有其他技术(例如Builder模式),但这是最基本且可理解的方法。 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. 例如,当我们给它命名和姓氏时,必须创建(实例化)像Student类的类。 Without them, create a Student is not good because maybe we forget to give it proper name and use it incorrectly. 没有他们,创建一个Student不好,因为也许我们忘记给它起适当的名字而错误地使用了它。 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). 当你想创建一个Student这是一个Humanextends Human )必须先创建Human你里面Student ,并设置特殊的功能为您的学生像ID这是不是HumanHuman有名字和等)。 so when you create a Student with constructor, the super constructor (for Human ) is called too. 因此,当您使用构造函数创建Student时,也会调用超级构造函数(用于Human )。

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) (为了正确使用它们)每个子类都使用super()隐式调用超类构造函数,但是如果超类没有任何默认构造函数(不带参数的构造函数),则必须在子类的第一个留置权中明确说出super(...)构造函数(否则编译错误)

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. 我只提到了4和6。我试图完全解释。 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. 如果该类是子类,则需要在创建对象之前调用父类的构造函数,除非父类具有没有参数的构造函数,在这种情况下,如果您不指定任何内容,java可以为您调用它。 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. 您可以看到如何通过super()以及方法来调用父类的构造函数。 Here I have used methods like getEmployeeTitle() which should help you get an overview on how to write methods. 在这里,我使用了诸如getEmployeeTitle()之类的方法,该方法应该可以帮助您概述如何编写方法。 I have also overridden the toString() method so that you can understand how to override Object class' useful methods like toString(). 我还重写了toString()方法,以便您可以了解如何重写Object类的有用方法,例如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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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