Java Java Data Structures Getting There Type Casting

mohamadreza azadi
mohamadreza azadi
5,167 Points

where is our superclass

i little bit confused about superclass(or parent class) and childclass(or subclass) what is that class ? . can anyone explain simplistic for me ?

3 Answers

Dino Šporer
Dino Šporer
5,430 Points

If you want to have two classes, a police car and taxi car, you would write two classes with same methods and functions, That means you will be repeating yourself. But you can use inheritance, from super class car, inherit all methods and fields, and add for example field isTexiFree, or isPoliceChasingSomeone, and you would do it in few lines of code, instead of 100 without inheritance.

mohamadreza azadi
mohamadreza azadi
5,167 Points

wow awsome if you can example with code for me I'm very ashamed.

Dino Šporer
Dino Šporer
5,430 Points

That class you often find in Java documentation. It's something like Object documentatio. There you can find all subclasses you been using and they inherited from parent class.

Here is good explanation!

https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

mohamadreza azadi
mohamadreza azadi
5,167 Points

it's good resource but i dont know what is that class i mean i dont understant parent class what is it

Dino Šporer
Dino Šporer
5,430 Points

public class Bicycle { the Bicycle class has three fields public int cadence; public int gear; public int speed;

// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

} ok, now if you do this :

public class MountainBike extends Bicycle {

// the MountainBike subclass adds one field
public int seatHeight;

}

Mountain bike now will have fields cadence, gear, speed and + seatHeight ! :D

and now, you have to make a constructor. In this constructor you can call contructor from Bicycle with keyword super, something like this :

public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear);

    plus one variable you added in MountainBike. 
    seatHeight = startHeight;
}   

I hope this is enough for u to understand inheritance!