Classes
We've already seen classes from previous examples like class Vehicle. In object-oriented programming (OOP), we always create the most common or generalized class.
Ex.
public class Vehicle{
}
We created the class as Vehicle and from that, we put methods that is common to all vehicles.
Ex.
public class Vehicle{
public void accelerate(){
}
public void decelerate(){
}
public void start(){
}
public void stop(){
}
public void turnDirection(){
}
}
Then we create a “sub-class” called “Car”:
public class Car extends Vehicle{
public void turnOnRadio(){
}
public void turnOnWiper(){
}
}
And, also inheriting from Vehicle class we create:
public class Bicycle extends Vehicle{
public void adjustMirror(){
}
public void soundRinger(){
}
}
The Car and Bicycle are called sub-classes and Vehicle is the super class. We call this “inheritance.”
Then we can access the super class methods in our code.
Ex.
public static void main(String[] args){
Car car1 = new Car();
car1.start(); //since we inherited the methods in super class Vehicle, we can call its methods.
car1.accelerate();
car1.turnOnRadio(); //we can also use Car's own methods.
car1.stop();
Note: We can also use Vehicle's properties such as variables, constructors by using the super keyword, and even the super class' overriding methods.
Ex.
public class Vehicle{
public void start(){
System.out.println(“Start your engines”);
}
}
public class Car extends Vehicle(){
public void start(){
super.start();
}
}
Example of executing constructors in super class:
public class Vehicle{
public Vehicle(){
}
}
public class Car extends Vehicle{
public Car(){
super();
}
}
It can also pass in arguments:
public Car(int wheels, int doors){
super(wheels,doors)
}
to be continued...
No comments:
Post a Comment