JavaRush /Java Blog /Random EN /instanceof and inheritance basics

instanceof and inheritance basics

Published in the Random EN group
Hello! In previous lectures, we have already briefly encountered the concept of inheritance several times. Today we will also touch on this topic, but also not too deeply. There will be a detailed lecture about this later, but today we’ll just look at practical examples and get acquainted with one interesting operator in Java.

Java inheritance

So, what exactly is inheritance? instanceof and inheritance basics - 1Inheritance is a mechanism in programming, including Java, that allows you to describe a new class based on an existing one. The descendant class then gains access to the fields and methods of the parent class. Why might this be necessary? Well, for example, imagine that you need to create several classes of cars in the program: Truck, Racing, Sedan, Pickup, etc. Even without starting to write code, you know for sure that these classes have a lot in common: all cars have a model name, year of manufacture, engine size, maximum speed, etc. (not to mention the fact that they all have wheels and other parts). In such a situation, you can:
  • Create these fields in each class and add them to new car classes when they are created
  • Move the fields common to all machines into the parent class Car, and all classes of specific types of machines inherit from Carusing the word extends .
The second option, of course, is much more convenient:
public class Car {

   private String model;
   private int maxSpeed;
   private int yearOfManufacture;

   public Car(String model, int maxSpeed, int yearOfManufacture) {
       this.model = model;
       this.maxSpeed = maxSpeed;
       this.yearOfManufacture = yearOfManufacture;
   }
}

public class Truck extends Car {

   public Truck(String model, int maxSpeed, int yearOfManufacture) {
       super(model, maxSpeed, yearOfManufacture);
   }
}

public class Sedan extends Car {
   public Sedan(String model, int maxSpeed, int yearOfManufacture) {
       super(model, maxSpeed, yearOfManufacture);
   }
}
At a minimum, we have avoided unnecessary duplication of code, and this is something we should always strive for when writing programs. In addition, we have a simple and understandable class structure: fields common to all machines are placed in one class. If, for example, trucks have some specific fields that other cars do not, they can be declared in the Truck. The same goes for methods. All cars have some common behavior that can be described: start the car, gas/brake, etc. These general methods can be placed in a general class Car, and the specific behavior of each specific type can be described in descendant classes.
public class Car {

   public void gas() {
       //...gas
   }

   public void brake() {
       //...brake
   }
}


public class F1Car extends Car {

   public void pitStop() {

       //...only racing cars make pit stops
   }

   public static void main(String[] args) {

       F1Car formula1Car = new F1Car();
       formula1Car.gas();
       formula1Car.pitStop();
       formula1Car.brake();
   }
}
We have moved the common methods of all cars into the class Car. But in the successor class F1Car, which describes Formula 1 racing cars - pit stops (stops for urgent maintenance of the car), which are done only in racing and are distinguished by specific behavior.

Java instanceof operator

To check whether an object is created based on a class, there is a special operator in Java - instanceof. It returns the value trueif the test was true, or falseif the result was false. Let's see how it works using our car classes as an example:
public class Truck extends Car {

   public static void main(String[] args) {

       Truck truck = new Truck();
       System.out.println(truck instanceof Car);
   }
}
Output: true Testing using the operator instanceofreturned true, since we have an object of the class Truck, and all trucks are cars. The class Truckis a descendant of the class Car, therefore, all trucks are created based on a common parent - a car. Pay attention to the operator instanceof: it is written without a dot, since it is an operator, not a method (“object instanceof Class”). Let's try it differently:
public static void main(String[] args) {

   Car car = new Car();
   System.out.println(car instanceof Truck);
}
Output: false The class Carand, accordingly, its object do not derive from the class Truck.All trucks are cars, but not all cars are trucks. Objects Carare not created based on the class Truck. One more example:
public static void main(String[] args) {

   Car car = new Car();
   Truck truck = new Truck();
   System.out.println(car instanceof Object && truck instanceof Object);
}
Output: True The logic here is also simple: all classes in Java, including those that you created, come from a class Object(although you do not write extends Object in them - this mechanism is implicit in them). Why might this be useful and under what circumstances? The most common use of the operator instanceofis as a method override equals(). For example, here is how the method is implemented equalsin the class String:
public boolean equals(Object anObject) {
   if (this == anObject) {
       return true;
   }
   if (anObject instanceof String) {
       String anotherString = (String) anObject;
       int n = value.length;
       if (n == anotherString.value.length) {
           char v1[] = value;
           char v2[] = anotherString.value;
           int i = 0;
           while (n-- != 0) {
               if (v1[i] != v2[i])
                       return false;
               i++;
           }
           return true;
       }
   }
   return false;
}
Before comparing the string with the passed object, the method checks: is the passed object actually a string? And only then does he begin to compare the properties of two objects. Without this check, you could pass any object that has value and length fields into the method and compare it with a string, which, of course, would be wrong.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION