简体   繁体   中英

Can a Object have method or variable which is not define in a class?

我知道这是愚蠢的,但我想确定。在面向对象的语言中,是否有任何情况或机会,从特定类创建的对象可以有一个没有在该类中定义的方法或变量?

It is possible to have Variables and Methods in a Class which are not directly defined in it. This happens when you have an abstract class and a child class (a class which extends the abstract class).

It is actually a very common approach when it comes to OOP to have a much better reusability of your Codebase.

Imagine you have an abstract class called Vehicle which looks like this:

public abstract class Vehicle {

protected enum Condition {
    BAD,
    OK,
    GOOD
}

private int numOfWheels;
private int numOfSeats;
private boolean isDriving;
private boolean isMotorized;
private Condition condition;

public Vehicle(int numOfWheels,
               int numOfSeats,
               boolean isDriving,
               boolean isMotorized,
               Condition condition) {
    this.numOfWheels = numOfWheels;
    this.numOfSeats = numOfSeats;
    this.isDriving = isDriving;
    this.isMotorized = isMotorized;
    this.condition = condition;
}

protected void repair() {
    if(!this.condition.equals(Condition.GOOD)) {
        this.condition = Condition.GOOD;
    }
}

Then you have a child class called Car which could look something like this:

public class Car extends Vehicle {
private String brand;
private String model;

public Car(int numOfSeats,
           boolean isDriving,
           Condition condition,
           String brand,
           String model) {
    super(4, numOfSeats, isDriving, true, condition);
    this.brand = brand;
    this.model = model;
}

The Constructor in your Car class first calls the super Constructor in your parent class with the given parameters and then sets the specific variables for your Car Object.

You can then call your Car construcor with something like this:

Car car = new Car(2, false, Vehicle.Condition.BAD, "Mercedes", "AMG");

So if you want to call the repair Method now, which is defined in your abstract class Vehicle, you can simply do this call:

car.repair();

What we have achieved with this Architecture is that everytime we want to create an Object which is a Vehicle like a Bicycle for example, we only have to declare some specific variables or Methods like we did in the Car class and not the same over and over again.

In much bigger Projects this can save you a lot of work and make your life easier.

I hope my explanation could help you understand the principle of OOP.

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