Java Basics For Beginners - 01 Class | Interface | Abstract Class

 Basic Building Blocks of Java 

Class

Class is the blueprint of an object. Let's explain this from a real-world example. For that, we will consider the Fish category. Fish is a common category it has specific behaviors and states. In the real world, we can see the implementation of Fish such as TankCleaners, Goldfish, and so on. This Fish is virtual and has specific behaviors and states but has no implementation of the behaviors. We cannot define the implementation of Fish behaviors because it is common. In java to define those virtual things, we use Interfaces. We cannot build an active object from the Interfaces. It is as we cannot find Fish in the real world there are only TacnkCleaners, GoldFish, and so on. 

In java to define the structure of real-world existing things, we use class

class GoldFish{
    String color;
    public void swim(){
        System.out.println("Gold fish swim in this way...");
    }
}

class is a keyword in java that is used to create a blueprint of an object.

Syntax to Create a class in Java

  • Java class name should be a noun in UpperCamelCase, with the first letter of every word capitalized. Ex: GoldFish
  • Class name also called as identifier in java identifier cannot begin with number.

Interface

Interface is used to represent virtual entity like Fish. In the interfaces there are no behavior  implementation only declaration of the behavior. And interface in java is a blueprint of class.
Let's discuss more about interfaces later when we discuss about object oriented concepts.

interface Fish {
    public abstract void swim();
}

Abstract Class

Abstract class can be use in a situation like, we know implementation of some behaviors of a realword object and don't know about some behaviors.  Think about Man class, it has some behaviors like eat, walk, talk, breath and so on. Here all mans are not eating , talking and walking in similar way so we cannot define implementation of those behaviors. But all mans are breathin in similar way. Then we can difine the implementation of that behavior to represent this kind of classes we use Abstract classes. To declar abstract class it use abstract keyword in java.

abstract  class Man {
    public abstract void eat();
    public abstract void talk();
    public abstract void walk();
   
    public void breath(){
        System.out.println("Mans breathing in this way...");
    }
}

Comments

Popular posts from this blog

History of java