简体   繁体   English

为什么我们需要在子类中创建方法以使用Java编程语言在Superclass中访问方法?

[英]Why we need to create method in subclass to acess methods in Superclass in Java programming language.?

I am currently learning OOP in java. 我目前正在用Java学习OOP。 One thing I came across is that, for example, i have a method speed in Vehicle SUPERCLASS, and I want to access that method in SUBCLASS Car, i will have to create method like; 我碰到的一件事是,例如,我在Vehicle SUPERCLASS中有一个方法速度,而我想在SUBCLASS Car中访问该方法,我将不得不创建类似的方法。

public void changespeed()
{
  super.speed();
}

in order to access speed method. 为了访问速度的方法。 My question is, why we need to enclose speed method like that in order to access it? 我的问题是,为什么要封装这样的速度方法才能访问它? why cant we just simply use this approach; 为什么我们不能简单地使用这种方法?

super.speed();

to call that speed method in subclass. 在子类中调用该speed方法。 ?

You can just do this: 您可以这样做:

speed();

Since non-private superclass methods are all inherited by the subclass, speed also exists in the subclass. 由于非私有超类方法都由子类继承,因此speed也存在于子类中。 You can access it by this.speed() , or just speed() . 您可以通过this.speed()或仅speed()来访问它。

Obviously, you have to put this method call in an appropriate place. 显然,您必须将此方法调用放在适当的位置。 You can't just randomly put it in a class like this: 您不能只是将其随机放入这样的类中:

class Car extends Vehicle {
    speed(); // can't do this!
}

You have to put the method call in, among other things, another method or a constructor. 除其他外,您必须将方法调用放入另一个方法或构造函数中。 This way the compiler knows when the method will be called. 这样,编译器便知道何时调用该方法。

Why do method calls have to be in other methods or constructors? 为什么方法调用必须位于其他方法或构造函数中?

Well, ask yourself when the method call in the above snippet will be called. 好吧,问问自己上述片段中的方法调用何时会被调用。 Remember that speed is an instance method, so an instance of Car is needed to call it. 请记住, speed是一个实例方法,因此需要一个Car实例来调用它。 Where's that instance? 那个实例在哪里? This whole notion of putting methods directly in a class makes little sense. 将方法直接放在类中的整个概念毫无意义。

So what if I want a method to be called when the class is loaded? 那么,如果我希望在加载类时调用一个方法怎么办?

You can use a static block for that purpose: 您可以为此使用静态块:

static {
    // do stuff here
}

Note that you still can't call speed directly in a static block because you need an instance of Car or Vehicle . 请注意,由于仍需要CarVehicle的实例,因此仍然无法在静态块中直接调用speed

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

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