this and super keywords in Java

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class.

The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

class Counter {
    int i = 0;

    Counter increment() {
        i++;
        return this;
    }

    void print() {
        System.out.println("i = " + i);
    }
}

public class CounterDemo extends Counter {
    public static void main(String[] args) {
        Counter x = new Counter();
        x.increment().increment().increment().print();
    }
}

 

Output:
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

class Vehicle
{
    // Instance fields
    int noOfTyres; // no of tyres
    private boolean accessories; // check if accessorees present or not
    protected String brand; // Brand of the car // Static fields
    private static int counter; // No of Vehicle objects created //
    Constructor Vehicle()
    {
        System.out.println("Constructor of the Super class called");
        noOfTyres = 5;
        accessories = true; brand = "X"; counter++;
     } // Instance methods
    public void switchOn()
    {
        accessories = true;
    }
    public void switchOff()
    {
        accessories = false;
    }
    public boolean isPresent()
    {
        return accessories;
    }
    private void getBrand()
    {
        System.out.println("Vehicle Brand: " + brand);
    } // Static methods
    public static void getNoOfVehicles()
    {
        System.out.println("Number of Vehicles: " + counter);
    }
}
class Car extends Vehicle
{
    private int carNo = 10;
    public void printCarInfo()
    {
        System.out.println("Car number: " + carNo);
        System.out.println("No of Tyres: " + noOfTyres); // Inherited. //
        System.out.println("accessories: " + accessories); // Not Inherited.
        System.out.println("accessories: " + isPresent()); // Inherited. //
        System.out.println("Brand: " + getBrand()); // Not Inherited.
        System.out.println("Brand: " + brand); // Inherited. //
        System.out.println("Counter: " + counter); // Not Inherited.
        getNoOfVehicles(); // Inherited.
     }
}
public class VehicleDetails
    {
         // (3)
         public static void main(String[] args)
        {
                new Car().printCarInfo();
        }
     }

 

Output:
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1

Inheritance in Java

In this Tutorial you’l learn about inheritance in Java. Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.

For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.

class Box {
    double width;
    double height;
    double depth;

    Box() {
    }

    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    void getVolume() {
        System.out.println("Volume is : " + width * height * depth);
    }
}

public class MatchBox extends Box {
    double weight;

    MatchBox() {
    }

    MatchBox(double w, double h, double d, double m) {
        super(w, h, d);

        weight = m;
    }

    public static void main(String args[]) {
        MatchBox mb1 = new MatchBox(10, 10, 10, 10);
        mb1.getVolume();
        System.out.println("width of MatchBox 1 is " + mb1.width);
        System.out.println("height of MatchBox 1 is " + mb1.height);
        System.out.println("depth of MatchBox 1 is " + mb1.depth);
        System.out.println("weight of MatchBox 1 is " + mb1.weight);
    }
}

Output:
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

Interfaces vs Abstract Classes

1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn’t contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword “abstract” keyword followed by Class definition. An Interface definition begins with the keyword “interface”.

3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast

10. Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.
Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.
Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they
share is a set of method signatures, then tend towards an interface.

Similarities:
Neither Abstract classes nor Interface can be instantiated.

Polymorphism in Java

Polymorphism means one name, many forms. There are 3 distinct forms of Java Polymorphism;
Method overloading (Compile time polymorphism)
Method overriding through inheritance (Run time polymorphism)
Method overriding through the Java interface (Run time polymorphism)
Polymorphism allows a reference to denote objects of different types at different times during execution. A super type reference exhibits polymorphic behavior, since it can denote objects of its subtypes.

interface Shape {
    public double area();

    public double volume();
}

class Cube implements Shape {
    int x = 10;

    public double area() {
        return (6 * x * x);
    }

    public double volume() {
        return (x * x * x);
    }
}

class Circle implements Shape {
    int radius = 10;

    public double area() {
        return (Math.PI * radius * radius);
    }

    public double volume() {
        return 0;
    }
}

public class PolymorphismTest {
    public static void main(String args[]) {
        Shape[] s = { new Cube(), new Circle() };
        for (int i = 0; i < s.length; i++) {
            System.out.println("The area and volume of " + s[i].getClass()
                    + " is " + s[i].area() + " , " + s[i].volume());
        }
    }
}

 

Output:
The area and volume of class Cube is 600.0 , 1000.0
The area and volume of class Circle is 314.1592653589793 , 0.0

The methods area() and volume() are overridden in the implementing classes. The invocation of the both methods area and volume is determined based on run time polymorphism of the current object as shown in the output.

Twitter Delicious Facebook Digg Stumbleupon Favorites More