Android : Basics of Java for Android Development part 2

Classes and Objects

Classes can be defined as a template or blueprint that describes the behaviors/states of its objects. Objects on the other hand have states and behaviors. For example, a car have states like – color, model, make, manufacturer, power etc and behavior as braking, speeding, emission, fuel consumption.A class is a blue print from which individual objects are created. For example:

public class Car{

    string color;
    string model;
    int make;
    string manufacturer;
    int power;

    void braking() {
    }

    void speeding() {
    }

    void emission() {
    }

    void fuelConsumption() {
    }
}

In the above example, color, model, make, manufacturer and power are called instance variables. These variables are created on creation of an object of the class. These variables have separate copies for every object of this class created. These variables can be accessed by any method(like braking, speeding, etc) that is defined in the class. If any variable is defined inside any of the method or block of code then it is called local variable. These variables are only accessible inside those methods or blocks. Finally third type of variables are class variables, these variables are also declared outside any method but with static keyword. These variables are common to all the objects of the class and can be modified by all of objects at the same time. A class can have any number of methods and variables.

Lets discuss constructors, every class has at least one constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class. Every object when initialized with new keyword, constructor will be called. Constructors have same name as that of the class and have no return types not even void.

class car {
    
    car(){
    }
    
    car(String color) {
        //this is a constructor with parameters and has one
        //parameter
    }
}

There are Class permissions and access modifiers that controls the visibility of a class members. Access modifiers are of 4 types: no modifier, public modifier, protected modifier and private modifier. In normal words, if you want to access something from anywhere make it public, if you want that methods or variables can only be accessed from within the class then you make them private and if you want that only this class and its sub-classes(inherited class, will discuss soon) can access variable or method then make them protected.

public class MyStuff {

    private String[] personal_items;
    public String[] open_items;
    protected String[] items_forSharing;
}

In the above example, Let suppose you have some stuff that you want to arrange using a class. You can divide your stuff in three broad categories, first those items that are personal to you and you don’t want to share it with anyone, “private” items, second those item that you can share with anyone, “public” items and last those items that you cannot share with others but with your known to, protected items.

Object Oriented Programming

Object Oriented Programming or OOP is a very-very wide concept and can’t be completed in-depth in this text’s context, so let’s have a very brief view of it. OOP is a technique that relies upon the definition of Objects. As an OOP language, Java supports the fundamental OOP concepts:

  • Encapsulation: wrapping up the data into one single module. In Java, Objects can have many variables and methods bind together to work as a single module or entity.
  • Abstraction: Hiding data and underlying implementation of the functionality from the outside world. In Java, abstraction is handled by classes, where the object just have the functionality and its implementation is hidden inside the blueprint of the class.
  • Inheritance: Inheritance is a way to create a class which is derived or based on other class in such a way that it extends the capabilities and/or modifies few functionality of the base class. This is one of the most used concept of Java in android application development and will be covered in little more details.
  • Polymorphism: polymorphism is a concept, that says that things behave differently in different situations(will be covered in more details later).

Inheritance

Inheritance is one of the most important Java concept and android heavily relies on it. In simple words, inheritance means organisation of classes from more general class to more specific classes. For example, lets suppose we have a class shape, it more generic class because shapes can be of a lot of types. Shape class will have instance variables like numberOfsides, parameter and area and methods like calculateArae(), calculateParamenter(). But if we have a class triangle then it has more specific nature. The triangle class will have all the properties of the shape class but will have its own properties too. The triangle class will have 3 as numberOfSides and has a different method to calculate the area(this will be covered in polymorphism).

public class Shape {
    
    protected int numberOfsides;
    private int[] sides;
    private int parameter;
    private int area;

    public Shape(int numberOfSides) {
        // feed the number to numberOfsides
    }

    public void setSides(int[] sides) {
        // feed the sides
    }

    public void calcParameter() {
        // calculate the parameter
    }

    public void calcArea() {
        // calculate the area
    }
}

public class Triangle extends Shape {

    public Triangle() {
        super(3);
    }

    @Override
    public void calcArea() {
        // calculate the area of the triangle
    }
}

As seen from the example, extends keyword is used to extend the base class into derived class. In Java, a derived class can extend one and only one base class and if base class has an explicit constructor then the derived class must have a constructor too whose first line is to call the super() which calls super class’s constructor. All the access modifiers have the same meaning as described earlier.

Polymorphism

Polymorphism is an important OOP concept and widely used in Java. Polymorphism advice use of common interface instead of concrete implementation. With polymorphism we don’t relay on concrete implementation and thus don’t require to change or duplicate most of our code to support new implementation. Java has excellent support of polymorphism in terms of Inheritance, method overloading and method overriding. Method overriding allows to pick the method based on particular object at run time.

public class Base {

    public void method() {
        //print "base"
    }
}

public class childA extends Base {

    @Override
    public void method() {
        //print "childA"
    }
}

public class childB extends Base {

    @Override
    public void method() {
        //print "childB"
    }
}

public class SomeClass {

    public static void main(String[] args) {
        Base obj1 = new Base();
        Base obj2 = new ChildA();
        Base obj3 = new ChildB();

        obj1.method();
        obj2.method();
        obj3.method();
    }
}

In the class SomeClass, all the objects obj1, obj2 and obj3 are of same type Base but have references of different classes. When method() is called from obj1, obj2 and obj3 the output will be base, childA and childB respectively, thus same method is behaving differently with different reference. So in the above example of shapes, the calcArea method will override the area method of the base class and when a reference of the Triangle class is calls the calcArea method, the overridden method will be called.

Interfaces

In Java, you can organised object behaviors with Interfaces. While a class is blueprint of the objects, an interface defines some behavior that can be added to the blueprint of the object. The class must define all the behaviors(methods) in the interface, thus it forces an organised structure of the classes of same type.

public interface Shape {

    void calcParameter();
    void calcArea();
}

public class Triangle implements Shape {
    //provide implementations of calcParameter() and calcArea() 
    //methods
}

public class Square implements Shape {
    //provide implementations of calcParameter() and calcArea()
    //methods
}

Inner Classes

This is the final topic in this Java tutorial. Inner classes are the classes that are defined inside another class or called outer class. We will also check anonymous inner classes, which will be encountered quite frequently while developing with Android SDK. Inner classes have all the features of a regular class, but their scope is limited. Inner classes have one big advantage that it have access to all the class variables and methods. Inner classes are only to help organize the code and compiler treats inner classes just like any other class.

public class MainClass {
    
    //Main class variables including objects of both partial
    //classes and methods.

    class InnerClassA {
        // Inner class variables and methods
        // can access Main class's variables and methods
    }

    class InnerClassB {
        // Inner class variables and methods
        // can access Main class's variables and methods.
    }
}

We cannot create objects of InnerClassA and InnerClassB outside of the MainClass class. These classes can only be instantiated with the MainClass. But InnerClasses could access any fields or methods available in the outer class MainClass, as needed.

Static Inner classes

One of the type of Inner classes is static nested class or static inner class. A static inner class defines behavior that is not tied to any object as static fields are not bound to any objects, thus applies across all instances.

public class MainClass {
    
    //Main class variables including objects of both partial
    //classes and methods.

    public static class InnerClass {
        // Inner class variables and methods
        // can access Main class's variables and methods
    }
}

public class SomeClass {
    
    public static void main(String[] args) {
        MainClass.InnerClass obj = new MainClass.InnerClass();
    }
}

The InnerClass is static, thus it does not have to instantiate with MainClass’s object and its public thus it can be accessed from anywhere, we can instantiate the InnerClass outside the MainClass. But the static inner class do not have access to the non-static members of the MainClass as they might not even instantiated yet. So, static nested class or static inner classes don’t have full access to all the members of the outer class, but can be instantiated outside the outer class.

Anonymous Inner Class

Android uses Anonymous inner classes to great extent. Anonymous inner classes allows the developer to create, define and use a custom object all in one line. To create an anonymous inner class, you only need to provide the right-hand side of the definition. Beginning with the new keyword, followed by the class or interface you wish to extend or implement, followed by the class definition. This will create the class and return it as a value which you can then use to call a method. The disadvantage of this is that the object can be used just once no other object can be created as the class name do not exists(anonymous dah!).

public interface SomeInterface {

    void method();
}

public Class SomeClass {
    
    public SomeInterface obj = new SomeInterface() {
    
        @Override
        public void method() {
            //Do something
        }
    };
}

In the above example, the interface SomeInterface was implemented using anonymous inner class and thus its object can be created (remember polymorphism).

Well, this is it for the Java for android tutorial. This tutorial was just to kick-start the android development process not a full-fledged Java tutorial, for that you can check Oracle Java tutorials.

 

Previous : Basics of Android Development part 1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: