Object Oriented Programming - AnsuDennis/Java GitHub Wiki

Class

Template for creating objects.

Object - instance of class. state(attribute value at that point of time) and behavior(methods supported by object)

**toString method **

Object method toString is used to print the content of an Object. If the toString method is not overridden in a class, the default toString method from Object class is invoked. This would print some hashcode as shown in the example "com.rithus.Animal@f7e6a96". However, if toString method is overridden, the content returned by the toString method is printed like "Animal [name=Tommy, type=Dog]". While overwriting the signature should remain same as public String toString(). Usually u will use IDE to insert the String withthe attributes u want to include in the toString

**equal method **

Equals method is used when we compare two objects. Default implementation of equals method is defined in Object class. The implementation is similar to == operator. Two object references are equal only if they are pointing to the same object. We need to override equals method, if we would want to compare the contents of an object.

Important things to consider when implementing equals method

Any equals implementation should satisfy these properties:

  1. Reflexive. For any reference value x, x.equals(x) returns true.
  2. Symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  3. Transitive. For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  4. Consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, if no information used in equals is modified.
  5. For any non-null reference value x, x.equals(null) should return false.

hashCode method

HashCode is commonly used in collections like HashMap. It is are used to decide which group (or bucket) an object should be placed into in HashMap like collections. A group of object's might share the same hashcode. The implementation of hash code decides effectiveness of Hashing. A good hashing function evenly distributes object's into different groups (or buckets).

A good hashCode method should have the following properties • If obj1.equals(obj2) is true, then obj1.hashCode() should be equal to obj2.hashCode() • obj.hashCode() should return the same value when run multiple times, if values of obj used in equals() have not changed. • If obj1.equals(obj2) is false, it is NOT required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.

Method overloading A method having the same name as another method (in same class or a sub class) but having different parameters is called an Overloaded Method. Example 1 doIt method is overloaded in the below example: class Foo{ public void doIt(int number){ } public void doIt(String string){ } } Example 2 Overloading can also be done from a sub class. class Bar extends Foo{ public void doIt(float number){ } }

Java Example • Constructors o public HashMap(int initialCapacity, float loadFactor) o public HashMap() { o public HashMap(int initialCapacity) • Methods o public boolean addAll(Collection<? extends E> c) o public boolean addAll(int index, Collection<? extends E> c)

Method Overriding Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method Overriding. Let’s define an Animal class with a method shout. public class Animal { public String bark() { return "Don't Know!"; } }

Let’s create a sub class of Animal – Cat - overriding the existing shout method in Animal. class Cat extends Animal { public String bark() { return "Meow Meow"; } }

Java Example : HashMap public int size() overrides AbstractMap public int size()

Interface

An interface defines a contract for responsibilities (methods) of a class. An interface is a contract: the guy writing the interface says, "hey, I accept things looking that way" Interface represents common actions between Multiple Classes. Example in Java api : Map interface, Collection interface.

From java 1.8 u can give default implementation for specific methods. This method need not be written again in implementation class

Variables in an interface are always public, static, final.Interface methods are by default public and abstract. Before Java 8, A concrete method (fully defined method) cannot be created in an interface.

interface ExampleInterface1 { //By default - public abstract. No other modifier allowed void method1();//method1 is public and abstract //private void method6();//COMPILER ERROR! //This method, uncommented, would have given COMPILER ERROR! //in Java 7. Allowed from Java 8. default void method5() { System.out .println("Method5"); } }

An interface can extend another interface. Consider the example below: interface SubInterface1 extends ExampleInterface1{ void method3(); } Class implementing SubInterface1 should implement both methods - method3 and method1(from ExampleInterface1) An interface cannot extend a class.

A class can implement multiple interfaces. It should implement all the method declared in all Interfaces being implemented. An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map.

abstract class An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. Abstract class can have abstract methods which need to be implemented by sub class.

public abstract class AbstractClassExample { public static void main(String[] args) { //An abstract class cannot be instantiated //Below line gives compilation error if uncommented //AbstractClassExample ex = new AbstractClassExample(); } }

If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class. • An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines. o example abstract method : public abstract Set> entrySet(); • Another Example - Spring AbstractController

In code below “AbstractClassExample ex = new AbstractClassExample();” gives a compilation error because AbstractClassExample is declared with keyword abstract. Example in Java : HashMap & TreeMap extend AbstractMap.

An Abstract method does not contain body. An abstract method does not have any implementation. The implementation of an abstract method should be provided in an over-riding method in a sub class. //Abstract Class can contain 0 or more abstract methods //Abstract method does not have a body abstract void abstractMethod1(); abstract void abstractMethod2(); Abstract method can be declared only in Abstract Class. In the example below, abstractMethod() gives a compiler error because NormalClass is not abstract. class NormalClass{ abstract void abstractMethod();//COMPILER ERROR }

Abstract Class vs Interface Syntactical Differences

  • Methods and members of an abstract class can have any visibility. All methods of an interface must be public.
  • A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface.
  • A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define all interface methods as public

Constructor

Constructor is invoked whenever we create an instance(object) of a Class. We cannot create an object without a constructor. Constructor has the same name as the class and no return type. It can accept any number of parameters.

Default Constructor is the constructor that is provided by the compiler. It has no arguments. In case the class has a constructor defined in it then the default constructor will not be provided by the compiler. in such cases u will get compiler error when u try to invoke default constructor

super() A constructor can call the constructor of a super class using the super() method call. Only constraint is that it should be the first statement public Animal() { super(); this.name = "Default Name"; }

this() using this({parameters}) method call another constructor in the same class can be invoked from a constructor. public Animal() { this("Default Name"); } public Animal(String name) { this.name = name; }

Please note that a constructor cannot be explicitly called from any method except another constructor. class Animal { String name; public Animal() { } public method() { Animal();// Compiler error } }

If a super class constructor is not explicitly called from a sub class constructor, super class (no argument) constructor is automatically invoked (as first line) from a sub class constructor. Consider the example below: class Animal { public Animal() { System.out.println("Animal Constructor"); } } class Dog extends Animal { public Dog() { System.out.println("Dog Constructor"); } } class Labrador extends Dog { public Labrador() { System.out.println("Labrador Constructor"); } } public class ConstructorExamples { public static void main(String[] args) { Labrador labrador = new Labrador(); } } Program Output Animal Constructor Dog Constructor Labrador Constructor this is because compiler by default call super()