D
D
dieillusion2015-07-23 19:14:25
Java
dieillusion, 2015-07-23 19:14:25

How is inheritance (extends) different from creating new class instances (new)?

You can create new class instances or instances. For example, there was a Car class, and we created two instances of car1 and car2.

Car car1 = new Car;
Car car2 = new Car;

And you can also inherit a class, for example, there was a class Car, and we create classes Car1 and Car2.
class Car1 extends Car {
}
class Car2 extends Car {
}

How are these methods fundamentally different and how are they similar?
I am new to Java and please explain in simple language, google did not work.
Thanks in advance for your replies.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D', 2015-07-23
@Denormalization

The Car class is a stencil.
The new operator is the creation of a PRODUCT according to this stencil
extends is the creation of a new stencil (possibly with additions) by which products can be created.
Is there a difference between creating a product and creating a new stencil?

A
abs0lut, 2015-07-23
@abs0lut

Your example does not contain code, so it is not correct.
What if we write like this:

class Vehicle {
    public speedUp (int newSpeed) {
        speed = newSpeed;
    }
}

class Car extends Vehicle {
    private boolean opened = false;
    public void openDoor {
        opened = true;
    }
}

class Tank extends Vehicle {
    private ammo = 10;
    public void fire(Vehicle enemy) {
        ammo -= 1;
    }
}

It will be more clearly seen why inheritance is needed. Now, in the Tank class and in the Car class, it is not necessary to describe identical methods separately, since they are placed in a common superclass.
A class is a template for objects. It defines what objects (fields) are characterized by and how they behave (methods). Inside the class, we describe its methods and fields, but to use them, you need to create instances of the class - objects.
Inheritance is used to get rid of code copying. If two classes have something in common (for example, the same methods), it may be worth making a more general class from which the other two are inherited.
TL;DR
As a result of inheritance, we get a simpler and shorter code. As a result of creating objects, we get the opportunity to operate with object data.
ps read some book where simple examples of encapsulation, polymorphism and inheritance will be described. For example, "Head First Java". Or you can refer to mini-course from Oracle - Oracle tutorial

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question