Posted in Java for Python Developers, Tech

Java For Python Developers 2 – OOP

This blog will focus on Object Oriented Programming concepts like Inheritance, Polymorphism and writing Packages, Interfaces and Abstract classes in Java.

Packages

Packages make a project organized. It creates a level of security by letting only the classes within that package have access, and it also provides name-scoping.

  • Some of them we have already come across are System (System.out.println), String, Math. They are from the package java.lang that is automatically included without having to import.
  • An import statement is written at the beginning of the code and is accessible throughout. An alternate way is to type the full name on each use in the code., i.e <pkg_name>.<class_name>
  • Java doesn’t compile the imported class. An import statement only saves time typing the full name of every class.

Inheritance

Public, Private, Protected and Default are called access controls. They control whether a variables or a methods can be inheritance or not.

  • Public members are inherited.
  • Private members are not inherited
  • Protected members can be access only by subclasses
  • Default can be accessed only within the same class. It doesn’t require a keyword.

Java does not support multiple inheritance, as it leads to the “Deadly Diamond of Death” problem. Lets see what that means.

180px-Diamond_inheritance.svg

The diamond problem is an ambiguity that arises when two classes B and C inherit from A and then when D inherits from B and C. Now, if there is a method in A that has been overridden by both B and C then which version of the method does D inherit? that of B or that of C? To avoid this problem, Java does not allow multiple inheritance.

Few other important aspects of inheritance:

  • A non-public class can be sub-classed only by the classes in the same package.
  • A class declared as final cannot be sub-classed anymore.
  • A class which has all private constructors cannot be sub-classed.
  • The keyword used is “extends”

Polymorphism

Polymorphism is having many forms of a method.

It is not a valid overloading if only the return type of a given method has been changed. To overload a method, the argument list has to be changed.

Abstract Class

  • Abstract Classes cannot be instantiated. The compiler will restrict instantiation of an abstract class. Whereas, concrete classes can be instantiated.
  • Abstract Methods must be overridden by the inherited class. Abstract methods do not have a body. It keeps a check to ensure that the inherited class implement them.
  • An abstract method should always be put in an abstract class.

Lets see how they are implemented in Java:

abstract class Pan extends Utensils { 
    public abstract void Material(); //an abstract method.
} 

Pan p; //works
p = new Spoon; //works
p = new Pan; //Compiler throws an error: Pan is abstract; cannot be instantiated

It is similar to that in Python. Lets see the implementation:

from abc import ABCMeta, abstractmethod #IMPORTANT

class animal:
     __metaclass__ = ABCMeta
    def delegate(self):
        self.action()

    @abstractmethod
    def action(self): pass

class tiger(animal): pass

A=animal()
t = tiger()

Interfaces

An interface can be presumed to be an extra feature that are not inherited from a parent class. This kind of helps overcome the drawback of not being able to inherit multiple classes.

  • An interface contains all “abstract” methods that the subclass is forced to implement. It can be perceived as a 100% abstract class
  • The keyword used is “implements”
  • Interfaces are always “public”. Methods in the interface are always “abstract”
  • A class can implement multiple interfaces which allows adding a number of features to a class making it more meaningful, in other words more real-word than the parent class.

Here’s an example:

interface Pet {      // all are the abstract methods.      abstractvoid wagTail(int a);      abstractvoid RunAround(int a);      abstractvoid EatFood(int a);  }

class Dog extends Animal implements Pet {}

Conclusion:

In this blogpost we learnt some Object Oriented Programming concepts in Java. We also learnt how to implement Packages, Abstract Classes and Interfaces. In the next blog will be a deep dive into Memory management and Garbage Collection.

The previous blog was about getting started with basic concepts like using Variables, write Classes, conditional statements, loops and built-in libraries.                                     Java for Python Developers 1 – Basics

Posted in Java for Python Developers, Tech

Java for Python Developers 1 – Basics

The intention of this blog is to talk about the similarities and differences between Python and Java. This will be a series of blogposts, this being the first. Through this blog I plan to help myself and other Python developers learn Java easily by relating it to similar concepts in Python. The focus of this post will be on learning Basic concepts and writing some simple code in Java.

Why learn Java?

  • Java is a very popular and a widely used Programming language. It is used in building large systems due to it’s powerful JVM that leads to faster execution. When an Application needs to scale-up, Java is the most popular choice in the industry.
  • It supports Concurrency.
  • Java has a good cross platform support.
  • It has a very strong IDE support making the developer’s life easier.
  • It imposes certain best practices. There is most likely, a single way of doing stuff and hence a bad programmer can only harm so much. :\ But in case of languages like Python, there are several ways of writing a piece of code and the onus is completely on the developer to use the most optimized one.

Classes and Objects:

The concept of Classes, Objects and Object Oriented programming is similar to Python. But here’s the catch:

googleapisjavapython

Each .java file can only have a single public class that contains the main function. This is to know the exact point in the file from which the application is supposed to be launched. The name of this public class should be same as the name of the .java file.

Variables:

Again, the concept is very similar to Python including the naming conventions.

Java cares about Type. An Elephant cannot be put in a basket meant for vegetables. This is very much unlike Python, which decides if we need a Basket or a Cage based on whether the source is an Elephant or a vegetable that we are dealing with. 🙂 Moreover,

  • variables declared as final cannot be reassigned, once assigned to some value.
  • A variable of a particular type can be assigned to another of the same type. Example, a variable of the type Tiger (Tiger t1 = new Tiger()) can be assigned to any another variable of the type Tiger. (Tiger t2 = new Tiger(); t2 = t1;)
  • Java is PASS-BY-VALUE.

Global Variables in Python can be used as global x = 3. Java has no concept of global variables as such. However, a variable marked as public, static and final acts as a globally available constant.

Conditional Statement:

if(var1 == var2) { <do this>
}

Iteration:

WHILE Loop:

Use while loop when we do not know the exact number of times to loop, in advance. In other words, when we have to loop until a condition is satisfied.

while(boolean condn) { <repeat this>
}

FOR Loop:

for(int i=0;i<anArray.length;i++){
<repeat array-length number of times>
}

Enhanced FOR loop: (For each loop)

String[] AnArray = {"John","Bob","Andy","George","Rachel"};
System.out.println("Names: ");
for(String name: AnArray) {
    System.out.println(name);
}
teach-2562905_1280
DO NOT forget the SEMICOLON;

Java Library or Java API

Let’s now writing some simple code in Java to achieve certain redundant tasks using the built-in Libraries.

ArrayList:

ArrayList can perform some frequently used operations on Lists which otherwise takes multiple lines of code and iterations to achieve the same. Similar to the built-in functions for a List in Python, elements can be added to the list, removed, check if an element is present in a list, get the size of the list, get the index of an element etc. as follows:

import java.util.ArrayList;
ArrayList<String> ListPlaces = new ArrayList<String>();
String p1 = new String("Switzerland");
String p2 = new String("Singapore");
ListPlaces.add(p1);
ListPlaces.add(0,p2); //0 - index where p1 should be added
System.out.println(ListPlaces);
System.out.println(ListPlaces.size());
System.out.println(ListPlaces.get(0));
System.out.println(ListPlaces.indexOf(p1));
System.out.println(ListPlaces.remove(1));
System.out.println(ListPlaces.contains(p2));
System.out.println(ListPlaces.isEmpty());

Generating a random number:

int Rand = (int) (Math.random() * 10);

*(int) -> Type casting the return value of the random() function to an integer.

Obtaining user input from command line:

import java.util.Scanner;
System.out.println("Please enter your name: ");
Scanner sc = new Scanner(System.in);
String username = sc.nextLine();

Let’s play Battleship

Here’s an example program, the battleship game written in Java. We will play this on command-line. The game randomly assigns 3 Battleships on a 7×7 board. It allows the user to guess the location. On successful identification of each ship, it says “kill”. When all the ships sink, games ends with a score.

There may be better ways of writing this code but at this stage, we are just trying to get a step closer to learning Java. Here’s an implementation of the battleship game.

This code is also available on Github: https://github.com/shilpavijay/Battleship

import java.util.*;
import java.io.*;

public class Battleship {
    private GameHelper helper = new GameHelper();
    private ArrayList<PlayBattleship> battleList = new ArrayList<PlayBattleship>();
    private int noOfGuesses = 0;

    private void setUpGame() {
        PlayBattleship ship1 = new PlayBattleship();
        ship1.setName("Maximus");
        PlayBattleship ship2 = new PlayBattleship();
        ship2.setName("Aloy");
        PlayBattleship ship3 = new PlayBattleship();
        ship3.setName("Agnes");
        battleList.add(ship1);
        battleList.add(ship2);
        battleList.add(ship3);
        System.out.println(battleList);

        System.out.println("Your goal is to sink the three ships: Maximus, Aloy and Agnes with the least number of guesses.");
        for (PlayBattleship shipToset : battleList) {
            ArrayList<String> newLocation = helper.placeShip(3);
            shipToset.setLocation(newLocation);
        }
    }

    private void startPlaying() {

        while(!battleList.isEmpty()) {
            String userGuess = helper.getUserInput("Enter a guess");
            checkUserGuess(userGuess);
        }
        finishGame();
    }


    private void checkUserGuess(String userGuess) {
        noOfGuesses++;
        String result = "miss";

        for(int i=0;i<battleList.size();i++) {
            result = battleList.get(i).checkTheGuess(userGuess);
            if(result.equals("hit")) {
                break;
            }
            if(result.equals("kill")) {
                battleList.remove(i);
                break;
            }
        }
        System.out.println(result);
    }

    void finishGame() {
        System.out.println("Wow!!! You sunk all the ships! Congrats!");
        if(noOfGuesses <= 18) {
            System.out.println("Score: Congrats, you sunk all ships in " + noOfGuesses + " guesses!");
        }
        else {
            System.out.println("You have exhausted your options! Sorry! Please try again!");
        }
    }

    public static void main(String[] args) {
        Battleship game = new Battleship();
        game.setUpGame();
        game.startPlaying();
    }
}
class PlayBattleship {
    private ArrayList<String> location;
    private String name;

    public void setLocation(ArrayList<String> battleList) {
        location = battleList;
    }

    public void setName(String n){
        name = n;
    }
    public String checkTheGuess(String choice) {
        String result = "miss";
        int index = location.indexOf(choice);
        if(index>=0) {
            location.remove(index);
            if (location.isEmpty()) {
                result = "kill";
                System.out.println("You sunk " + name + ":|");
            }
            else {
                result = "hit";
            }
        }
        return result;
    }
}
class GameHelper {
    private static final String alphabet = "abcdefg";
    private int gridlength = 7;
    private int gridSize = 49;
    private int[] grid = new int[gridSize];
    private int comcount = 0;

    public String getUserInput(String prompt) {
        String inputLine = null;
        System.out.println(prompt);
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            inputLine = input.readLine();
            if(inputLine.length() == 0) return null;
        }
        catch(IOException e){
            System.out.println("IOException: " + e);
        }
        return inputLine.toLowerCase();
    }

    public ArrayList<String> placeShip(int size) {
        ArrayList<String> cells = new ArrayList<String>();
        String temp = null;
        int [] curr = new int[size];
        int attempts = 0;
        boolean success = false;
        int location = 0;

        comcount++;
        int incr = 1;
        if((comcount % 2) == 0) {
            incr = gridlength;
        }

        while(!success & attempts++ < 200) {
            location = (int) (Math.random() * gridSize);
            int x = 0;
            success = true;
            while(success && x<size) {
                if(grid[location] == 0) {
                    curr[x++] = location;
                    location += incr;
                    if (location >= gridSize) {
                        success = false;
                    }
                    if (x>0 && (location % gridlength == 0)) {
                        success = false;
                    }
                }
                else {
                    success = false;
                }
            }
        }

        int x = 0;
        int row = 0;
        int column = 0;

        while (x < size) {
            grid[curr[x]] = 1;
            row = (int) (curr[x]/gridlength);
            column = curr[x] % gridlength;
            temp = String.valueOf(alphabet.charAt(column));

            cells.add(temp.concat(Integer.toString(row)));
            x++;
//            System.out.print(" co-ord "+x+" = " + cells.get(x-1).toUpperCase());
        }
        return cells;
    }
}

Conclusion:

In this blogpost we learnt how to use Variables, write Classes, conditional statements, loops in Java. We also glanced at some basics APIs or built-in libraries in Java that help perform certain redundant operations easily. We also put these concepts in action by coding a game.