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.

Interfaces in Java

In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated.
Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.
If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class.

Example 1: Below is an example of a Shape interface

    interface Shape
     {
        public double area();
        public double volume();
    }

Below is a Point class that implements the Shape interface.

public class Point implements Shape
{
    static int x, y;
    public Point()
    {
        x = 0; y = 0;
    }
    public double area()
    {
        return 0;
    }
    public double volume()
    {
        return 0;
    }
    public static void print()
    {
        System.out.println("point: " + x + "," + y);
    }
    public static void main(String args[])
    {
        Point p = new Point(); p.print();
    }
}

 

Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface.
Example 2: Below is a java interfaces program showing the power of interface programming in java
Listing below shows 2 interfaces and 4 classes one being an abstract class.
Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. The classes B1
and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the implemented interface I2, the class D1 is declared abstract.
Also,
i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.
When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as every interface or class extends Object and any class can override the default toString() to suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they are “siblings”. You can’t cast siblings into one another.
When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and overridden methods.

    interface I1
    {
        void methodI1(); // public static by default
    }
    interface I2 extends I1
    {
        void methodI2(); // public static by default
    }
    class A1
    {
        public String methodA1()
        {
            String strA1 = "I am in methodC1 of class A1";
            return strA1;
        }
        public String toString()
        {
            return "toString() method of class A1";
        }
    }
    class B1 extends A1 implements I2
    {
        public void methodI1()
        {
            System.out.println("I am in methodI1 of class B1");
        }
        public void methodI2()
        {
            System.out.println("I am in methodI2 of class B1");
        }
    }
    class C1 implements I2
    {
        public void methodI1()
        {
            System.out.println("I am in methodI1 of class C1");
        }
        public void methodI2()
        {
            System.out.println("I am in methodI2 of class C1");
        }
    } // Note that the class is declared as abstract as it does not // satisfy the interface contract
abstract class D1 implements I2
{
        public void methodI1()
        {
        } // This class does not implement methodI2() hence declared abstract.
}
public class InterFaceEx
{
        public static void main(String[] args)
        {
            I1 i1 = new B1();
            i1.methodI1(); // OK as methodI1 is present in B1
            // i1.methodI2(); Compilation error as methodI2 not present in I1
            // Casting to convert the type of the reference from type I1 to type I2 ((I2) i1).methodI2(); I2 i2 = new B1(); i2.methodI1();
            // OK i2.methodI2(); // OK
            // Does not Compile as methodA1() not present in interface reference I1
            // String var = i1.methodA1();
            // Hence I1 requires a cast to invoke methodA1 String var2 = ((A1) i1).methodA1();
            System.out.println("var2 : " + var2);
            String var3 = ((B1) i1).methodA1();
            System.out.println("var3 : " + var3);
            String var4 = i1.toString();
            System.out.println("var4 : " + var4);
            String var5 = i2.toString();
            System.out.println("var5 : " + var5);
            I1 i3 = new C1(); String var6 = i3.toString();
            System.out.println("var6 : " + var6); // It prints the Object toString() method
            Object o1 = new B1();
            // o1.methodI1(); does not compile as Object class does not define
            // methodI1()
            // To solve the probelm we need to downcast o1 reference. We can do it
            // in the following 4 ways ((I1) o1).methodI1();
            // 1 ((I2) o1).methodI1();
            // 2 ((B1) o1).methodI1();
             // 3
            /* * * B1 does not have any relationship with C1 except they are "siblings". * * Well, you can't cast siblings into one another. * */ // ((C1)o1).methodI1(); Produces a ClassCastException
        }
}

 

Output:
I am in methodI1 of class B1
I am in methodI2 of class B1
I am in methodI1 of class B1
I am in methodI2 of class B1
var2 : I am in methodC1 of class A1
var3 : I am in methodC1 of class A1
var4 : toString() method of class A1
var5 : toString() method of class A1
var6 : C1@190d11
I am in methodI1 of class B1
I am in methodI1 of class B1
I am in methodI1 of class B1

Abstract classes in Java

Abstract Class:
Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.
Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.
A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.

abstract class Vehicle
    {
        int numofGears;
        String color;
        abstract boolean hasDiskBrake();
        abstract int getNoofGears();
    }

 

Example of a shape class as an abstract class

abstract class Shape
    {
        public String color; public Shape()
        {
        }
        public void setColor(String c)
        {
            color = c;
        }
        public String getColor()
        {
            return color;
        }
        abstract public double area();
    }

 

We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

public class Point extends Shape
{
    static int x, y;
    public Point()
    {
        x = 0;
        y = 0;
    }
    public double area()
    {
        return 0;
    }
    public double perimeter()
    {
         return 0;
    }
    public static void print()
    {
        System.out.println("point: " + x + "," + y);
     }
    public static void main(String args[])
    {
        Point p = new Point(); p.print();
    }
}

 

Output:
point: 0, 0
Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methods of the Shape class must be implemented by the Point class.
The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

Introduction to Access Modifiers in Java

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

Access Modifiers
1. private
2. protected
3. default
4. public

public access modifier:

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

private access modifier:
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

protected access modifier:

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

default access modifier:
Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers. The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below.

package pckage1;
class BaseClass
{
    public int x = 10;
    private int y = 10;
    protected int z = 10;
    int a = 10; //Implicit Default Access Modifier
    public int getX()
    {
        return x;
    }
    public void setX(int x)
    {
        this.x = x;
        }
    private int getY()
    {
        return y;
        }
    private void setY(int y)
    {
        this.y = y;
        }
    protected int getZ()
    {
        return z;
        }
    protected void setZ(int z)
    {
        this.z = z;
        }
    int getA()
    {
        return a;
        }
    void setA(int a)
    { this.a = a;
}
    }
public class SubclassInSamePackage extends BaseClass
{
    public static void main(String args[])
    {
        BaseClass rr = new BaseClass();
        rr.z = 0;
        SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public
        System.out.println("Value of x is : " + subClassObj.x);
        subClassObj.setX(20);
        System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /*
        System.out.println("Value of y is : "+subClassObj.y);
        subClassObj.setY(20);
        System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected
        System.out.println("Value of z is : " + subClassObj.z);
        subClassObj.setZ(30);
        System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default
        System.out.println("Value of x is : " + subClassObj.a);
        subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a);
        }
    }
    }
}

 

Output:
Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20

The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. This java class extends First class (SubclassInSamePackage.java).

import pckage1.*;
public class SubClassInDifferentPackage extends SubclassInSamePackage
{
    public int getZZZ()
    {
        return z;
    }
    public static void main(String args[])
    {
        SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage();
        SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access specifiers - Public
        System.out.println("Value of x is : " + subClassObj.x);
        subClassObj.setX(30);
        System.out.println("Value of x is : " + subClassObj.x); //Access specifiers - Private // if we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /*
        System.out.println("Value of y is : "+subClassObj.y);
        subClassObj.setY(20);
        System.out.println("Value of y is : "+subClassObj.y);*/ //Access specifiers - Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected. /*
        System.out.println("Value of z is : "+subClassObj.z);
        subClassObj.setZ(30);
        System.out.println("Value of z is : "+subClassObj.z);*/
        System.out.println("Value of z is : " + subClassDiffObj.getZZZ()); //Access Modifiers - Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default. /*
        System.out.println("Value of a is : "+subClassObj.a);
        subClassObj.setA(20); System.out.println("Value of a is : "+subClassObj.a);*/
        }
    }

 

Output:
Value of x is : 10
Value of x is : 30
Value of z is : 10

The third class is ClassInDifferentPackage.java which is present in a different package then the first one.

import pckage1.*;
public class ClassInDifferentPackage
{
    public static void main(String args[])
    {
        SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public
        System.out.println("Value of x is : " + subClassObj.x);
        subClassObj.setX(30);
        System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Private // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private
        /*
        System.out.println("Value of y is : "+subClassObj.y);
        subClassObj.setY(20);
        System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected.
        /*
        System.out.println("Value of z is : "+subClassObj.z);
        subClassObj.setZ(30);
        System.out.println("Value of z is : "+subClassObj.z);*/ //Access Modifiers - Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default.
        /*
        System.out.println("Value of a is : "+subClassObj.a);
        subClassObj.setA(20); System.out.println("Value of a is : "+subClassObj.a);*/
    }
}

 

Output:
Value of x is : 10
Value of x is : 30

Constructor Chaining in Java

Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.

class Cube {
    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    Cube() {
        this(10, 10);
        System.out.println("Finished with Default Constructor of Cube");
    }

    Cube(int l, int b) {
        this(l, b, 10);
        System.out
                .println("Finished with Parameterized Constructor having 2 params of Cube");
    }

    Cube(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
        System.out
                .println("Finished with Parameterized Constructor having 3 params of Cube");
    }
}

public class SpecialCube extends Cube {
    int weight;

    SpecialCube() {
        super();
        weight = 10;
    }

    SpecialCube(int l, int b) {
        this(l, b, 10);
        System.out
                .println("Finished with Parameterized Constructor having 2 params of SpecialCube");
    }

    SpecialCube(int l, int b, int h) {
        super(l, b, h);
        weight = 20;
        System.out
                .println("Finished with Parameterized Constructor having 3 params of SpecialCube");
    }

    public static void main(String[] args) {
        SpecialCube specialObj1 = new SpecialCube();
        SpecialCube specialObj2 = new SpecialCube(10, 20);
        System.out.println("Volume of SpecialCube1 is : "
                + specialObj1.getVolume());
        System.out.println("Weight of SpecialCube1 is : " + specialObj1.weight);
        System.out.println("Volume of SpecialCube2 is : "
                + specialObj2.getVolume());
        System.out.println("Weight of SpecialCube2 is : " + specialObj2.weight);
    }
}

Output:
inished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20

The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors.
if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.
Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.
Below is an example of a class demonstrating constructor chaining using explicit super() call.

class Cube
{
    int length;
    int breadth;
    int height;
    public int getVolume()
    {
        return (length * breadth * height);
    }
    Cube(int l, int b, int h)
    {
        length = l; breadth = b;
        height = h;
        System.out.println("Finished with Parameterized Constructor having 3 params of Cube");
    }
}
public class SpecialCube1 extends Cube
{
    int weight; SpecialCube1()
    {
        super(10, 20, 30); //Will Give a Compilation Error without this line weight = 10; } public static void main(String[] args) { SpecialCube1 specialObj1 = new SpecialCube1(); System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume()); } }
    }
}

 

Output:
inished with Parameterized Constructor having 3 params of Cube
Volume of SpecialCube1 is : 6000

Constructor Overloading in Java

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context:

public class Cube2 {
    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    Cube2() {
        this(10, 10);
        System.out.println("Finished with Default Constructor");
    }

    Cube2(int l, int b) {
        this(l, b, 10);
        System.out
                .println("Finished with Parameterized Constructor having 2 params");
    }

    Cube2(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
        System.out
                .println("Finished with Parameterized Constructor having 3 params");
    }

    public static void main(String[] args) {
        Cube2 cubeObj1, cubeObj2;
        cubeObj1 = new Cube2();
        cubeObj2 = new Cube2(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
        System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
    }
}

public class Cube2 {
    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    Cube2() {
        this(10, 10);
        System.out.println("Finished with Default Constructor");
    }

    Cube2(int l, int b) {
        this(l, b, 10);
        System.out
                .println("Finished with Parameterized Constructor having 2 params");
    }

    Cube2(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
        System.out
                .println("Finished with Parameterized Constructor having 3 params");
    }

    public static void main(String[] args) {
        Cube2 cubeObj1, cubeObj2;
        cubeObj1 = new Cube2();
        cubeObj2 = new Cube2(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
        System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
    }
}

 

Output :
Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

Introduction to Java Constructors

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1
    {
        int length;
        int breadth;
        int height;
        public int getVolume()
        {
            return (length * breadth * height);
         }
        Cube1()
        {
            length = 10;
            breadth = 10;
            height = 10;
        }
        Cube1(int l, int b, int h)
        {
            length = l;
            breadth = b;
            height = h;
        }
        public static void main(String[] args)
        {
            Cube1 cubeObj1, cubeObj2;
            cubeObj1 = new Cube1();
            cubeObj2 = new Cube1(10, 20, 30);

            System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
            System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
        }
     }

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.

Method Overloading in Java

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading:

public class MethodOverloadDemo
         {
            void sumOfParams()
            {
                // First Version
                System.out.println("No parameters");
            }
            void sumOfParams(int a)
            {
                 // Second Version
                System.out.println("One parameter: " + a);
             }
            int sumOfParams(int a, int b)
            {
                // Third Version
                System.out.println("Two parameters: " + a + " , " + b);
                return a + b;
             }
             double sumOfParams(double a, double b)
             {
                // Fourth Version
                System.out.println("Two double parameters: " + a + " , " + b);
                return a + b;
            }
             public static void main(String args[])
            {
                MethodOverloadDemo moDemo = new MethodOverloadDemo();
                int intResult;
                double doubleResult;
                moDemo.sumOfParams();
                System.out.println();
                moDemo.sumOfParams(2);
                System.out.println();
                intResult = moDemo.sumOfParams(10, 20);
                System.out.println("Sum is " + intResult);
                System.out.println();
                doubleResult = moDemo.sumOfParams(1.1, 2.2);
                System.out.println("Sum is " + doubleResult);
                System.out.println();
             }
        }

Output:
No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30
Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003

Introduction to Java Object Class

The Object Class is the super class for all classes in Java.
Some of the object class methods are

  • equals
  • toString()
  • wait()
  • notify()
  • notifyAll()
  • hashcode()
  • clone()

An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.

Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.

Below is an example showing the creation of Cube objects by using the new operator.

public class Cube
{
     int length = 10;
     int breadth = 10;
    int height = 10;
     public int getVolume()
    {
        return (length * breadth * height);
     }
     public static void main(String[] args)
    {
        Cube cubeObj; // Creates a Cube Reference
        cubeObj = new Cube(); // Creates an Object of Cube
        System.out.println("Volume of Cube is : " + cubeObj.getVolume());
     }
}

Understanding Java Classes and Objects

Introduction to Java Classes:
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.

A class has the following general syntax:

<class modifiers>class<class name>
<extends clause> <implements clause>{
// Dealing with Classes (Class body)
<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}

Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().

public class Cube
{
    int length;
    int breadth;
    int height;
    public int getVolume()
    {
         return (length * breadth * height);
    }
}


How do you reference a data member/function?
This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).
For example:
cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields
We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods
Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods.
You cannot call non-static methods from inside a static method.

Instance Variables
Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.

Consider this simple Java program showing the use of static fields and static methods:

    // Class and Object initialization showing the Object Oriented concepts in Java
            class Cube
             {
                 int length = 10;
                 int breadth = 10;
                 int height = 10;
                public static int numOfCubes = 0; // static variable
                public static int getNoOfCubes()
                {
                    //static method
                    return numOfCubes;
                }
                public Cube()
                {
                    numOfCubes++; //
                }
             }

         public class CubeStaticTest
        {
             public static void main(String args[])
             {
                 System.out.println("Number of Cube objects = " + Cube.numOfCubes);
                System.out.println("Number of Cube objects = " + Cube.getNoOfCubes());
             }
        }

Output
Number of Cube objects = 0
Number of Cube objects = 0

Final Variable, Methods and Classes:
In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.
Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.

Class Declaration in Java

A simple Java class declaration with constructor declaration:

class simple
{
    // Constructor
    simple()
    {
         p = 1;
         q = 2;
         r = 3;
     }
         int p,q,r;
}

In class declaration, you can declare methods of the class:

class simple
{
    // Constructor
    simple()
    {
        p = 1;
        q = 2;
        r = 3;
     }
         int p,q,r;
     public int addNumbers(int var1, int var2, int var3)
     {
        return var1 + var2 + var3;
     }
    public void displayMessage()
    {
        System.out.println("Display Message");             }
}

To invoke the class, you can create the new instance of the class:
// To create a new instance class
Simple sim = new Simple();
// To access the methods of the class
sim.addNumbers(5,1,2)
// To show the result of the addNumbers
System.out.println("The result is " + Integer.toString(addNumbers(5,1,2)));

The complete listing of class declaration:

    class simple
     {
        // Constructor
        simple()
        {
             p = 1;
             q = 2;
             r = 3;
         }
             int p,q,r;
         public int addNumbers(int var1, int var2, int var3)
         {
            return var1 + var2 + var3;
         }
         public void displayMessage()
         {
             System.out.println("Display Message");
         }
     }

class example1
{
    public static void main(String args[])
     {
        // To create a new instance class
        Simple sim = new Simple(); // To show the result of the addNumbers
         System.out.println("The result is " + Integer.toString(addNumbers(5,1,2))); // To display message
         sim.displayMessage();
    }
}

Introduction to Classes and Objects in Java

Everything in Java is either a class, a part of a class, or describes how a class behaves. Objects are the physical instantiations of classes. They are living entities within a program that have independent lifecycles and that are created according to the class that describes them. Just as many buildings can be built from one blueprint, many objects can be instantiated from one class. Many objects of different classes can be created, used, and destroyed in the course of executing a program. Programming languages provide a number of simple data types like int, float and String. However very often the data you want to work with may not be simple ints, floats or Strings. Classes let programmers define their own more complicated data types.

All the action in Java programs takes place inside class blocks, in this case the HelloWorld class. In Java almost everything of interest is either a class itself or belongs to a class. Methods are defined inside the classes they belong to. Even basic data primitives like integers often need to be incorporated into classes before you can do many useful things with them. The class is the fundamental unit of Java programs. For instance consider the following Java program:

class HelloWorld {
  public static void main (String args[]) {
    System.out.println("Hello World");
  }
}

Another Example:

class GoodbyeWorld {
  public static void main (String args[]) {
    System.out.println("Goodbye Cruel World!");
  }
}

Save this code in a single file called hellogoodbye.java in your javahtml directory, and compile it with the command javac hellogoodbye.java. Then list the contents of the directory. You will see that the compiler has produced two separate class files, HelloWorld.class and GoodbyeWorld.class. javac hellogoodbye.java

The second class is a completely independent program. Type java GoodbyeWorld and then type java HelloWorld. These programs run and execute independently of each other although they exist in the same source code file. 

Class Syntax:

Use the following syntax to declare a class in Java:
//Contents of SomeClassName.java
[ public ] [ ( abstract | final ) ] class SomeClassName [ extends SomeParentClass ] [ implements SomeInterfaces ]
{
        // variables and methods are declared within the curly braces
}

  • A class can have public or default (no modifier) visibility.
  • It can be either abstract, final or concrete (no modifier).
  • It must have the class keyword, and class must be followed by a legal identifier.
  • It may optionally extend one parent class. By default, it will extend java.lang.Object.
  • It may optionally implement any number of comma-separated interfaces.
  • The class's variables and methods are declared within a set of curly braces '{}'.
  • Each .java source file may contain only one public class. A source file may contain any number of default visible classes.
  • Finally, the source file name must match the public class name and it must have a .java suffix.

Here is an example of a Horse class. Horse is a subclass of Mammal, and it implements the Hoofed interface.

public class Horse extends Mammal implements Hoofed
{
         //Horse's variables and methods go here
}

Lets take one more example of Why use Classes and Objects. For instance let's suppose your program needs to keep a database of web sites. For each site you have a name, a URL, and a description. 

class website
{
     String name;
     String url;
     String description;
}


These variables (name, url and description) are called the members of the class. They tell you what a class is and what its properties are. They are the nouns of the class. members. A class defines what an object is, but it is not itself an object. An object is a specific instance of a class. Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class.
To instantiate an object in Java we use the new operator. Here's how we'd create a new web site:
website x = new website();
Once we've got a website we want to know something about it. To get at the member variables of the website we can use the . operator. Website has three member variables, name, url and description, so x has three member variables as well, x.name, x.url and x.description. We can use these just like we'd use any other String variables.

For instance:
    website x = new website();   
    x.name = "freehavaguide.com";
    x.url = "http://www.freejavaguide.com";
    x.description = "A Java Programming Website";
    System.out.println(x.name + " at " + x.url + " is " + x.description);

Declaring and Initializing 2-dimensional arrays Java Program

class Arrays3
{

    public static void main(String args[])
    {

        // this declares a 2-dimensional array named x[i][j] of size 4 (4 elements)
        // its elements are x[0][0], x[0][1], x[1][0] and x[1][1].
        // the first index i indicates the row and the second index indicates the
        // column if you think of this array as a matrix.

        int x[][] = new int[2][2];

        // print out the values of x[i][j] and they are all equal to 0.0.
        for(int i=0; i<=1; i++)
        for(int j=0; j<=1; j++)
        System.out.println("x["+i+","+j+"] = "+x[i][j]);

        // assign values to x[i]
        for(int i=0; i<=1; i++)
        for(int j=0; j<=1; j++)
        x[i][j] = i+j; // for example

        // print the assigned values to x[i][j]
        for(int i=0; i<=1; i++)
        for(int j=0; j<=1; j++)
        System.out.println("x["+i+","+j+"] = "+x[i][j]);

        // this declares a 2-dimensional array of type String
        // and initializes it
        String st[][]={{"row 0 column 0","row 0 column 1"}, // first row
        {"row 1 column 0","row 1 column 1"}}; // second row

        // print out st[i]
        for(int i=0; i<=1; i++)
        for(int j=0; j<=1; j++)
        System.out.println("st["+i+","+j+"] = "+st[i][j]);

    }
}

Find the sum of the numbers 2.5, 4.5, 8.9, 5.0 and 8.9 Java Program

        class Arrays2
        {

            public static void main(String args[])
            {

                // this declares an array named fl with the type "array of int" and
                // initialize its elements

            float fl[] = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f};   
            // find the sum by adding all elements of the array fl
            float sum = 0.0f;
            for(int i=0; i<= 4; i++)
            sum = sum + fl[i];

            // displays the sum
            System.out.println("sum = "+sum);
            }
        }

Check that the sum displayed is 29.8.

Declaring and Initializing 1-dimensional arrays Java Program

An array groups elements of the same type. It makes it easy to manipulate the information contained in them.

    class Arrays1
    {
        public static void main(String args[])
        {
            // this declares an array named x with the type "array of int" and of
            // size 10, meaning 10 elements, x[0], x[1] , ... , x[9] ; the first term
            // is x[0] and the last term x[9] NOT x[10].
            int x[] = new int[10];
            // print out the values of x[i] and they are all equal to 0.

        for(int i=0; i<=9; i++)
        System.out.println("x["+i+"] = "+x[i]);
        // assign values to x[i]

        for(int i=0; i<=9; i++)
        x[i] = i; // for example
        // print the assigned values of x[i] : 1,2,......,9

        for(int i=0; i<=9; i++)
        System.out.println("x["+i+"] = "+x[i]);
        // this declares an array named st the type "array of String"
        // and initializes it

        String st[]={"first","second","third"};
        // print out st[i]
    for(int i=0; i<=2; i++)
    System.out.println("st["+i+"] = "+st[i]);
        }
}

Multidimensional Arrays in Java

You don't have to stop with two dimensional arrays. Java lets you have arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you're probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.

The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. Here's a program that declares, allocates and initializes a three-dimensional array:

class Fill3DArray {
  public static void main (String args[]) {
    int[][][] M;
    M = new int[4][5][3];
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        for (int ver=0; ver < 3; ver++) {
          M[row][col][ver] = row+col+ver;
        }
      }
    }
  }
}

Twitter Delicious Facebook Digg Stumbleupon Favorites More