Thursday, May 15, 2014

Defining your first class in Java

A class is simply a category of objects. Each of these objects share common functionality and characteristics:
  • All cars have 4 wheels, an engine, a fuel tank etc.
  • All shapes have an area. (Though method of calculation may be different)
  • Each person has a name, age and gender.

Let's start with a classic example of a Animal class.

1:  abstract class Animal{  
2:    abstract void eat();  
3:    abstract void makeSound();  
4:  }  

The class is abstract as each kind of animal has a different behavior. In other words, the behavior is different for each kind of animal (for example, dogs bark and cats say "meow") and we cannot associate one general behavior with all kinds.

So the Animal class declares that all animals have some common behavior. abstract methods mean that each kind (or each subclass) of Animal will define its own way of making sounds and eating. 

Let's see a simple example

A dog is-a-kind-of Animal. So we define the following class:

1:  class Dog extends Animal{  
3:    //Following methods are common behavior   
4:    //declared in superclass Animal  
5:    //Now defined in a general way for Dog objects  
7:    void eat(){  
8:      System.out.println("Eating biscuits");  
9:    }  
11:    void makeSound(){  
12:      System.out.println("Barks...");  
13:    }  
14:  }  

This represents a blueprint of a Dog object.

Now let us test our code.

Full program:

1:  abstract class Animal{  
2:    abstract void eat();  
3:    abstract void makeSound();  
4:  }  
5:  class Dog extends Animal{  
7:    //Following methods are common behavior   
8:    //declared in superclass Animal  
9:    //Now defined in a general way for Dog objects  
11:    void eat(){  
12:      System.out.println("Eating biscuits");  
13:    }  
15:    void makeSound(){  
16:      System.out.println("Barks...");  
17:    }  
18:  }  
19:  class Test{  
20:      public static void main(String[] args){  
21:          System.out.println("Creating a new Dog object");  
22:          Dog dog = new Dog();  
23:          System.out.println("Calling eat() method on the Dog object");  
25:          System.out.println("Calling makeSound() method on the Dog object");  
26:          dog.makeSound();  
27:      }  
28:  }  

Running the code...

 D:\Dropbox\practice\blog>java Test  
 Creating a new Dog object  
 Calling eat() method on the Dog object  
 Eating biscuits  
 Calling makeSound() method on the Dog object  

This finishes the basics of defining your first class in Java.


Define two String variables in the Dog class. Both should be instance variables. One denotes the name of the dog and the other denotes the dog's breed. In the main method, print both the fields (without assigning any values). Now assign values to both the variables and print them again. Remember that you must use the dog variable to access the fields in main().

No comments :

Post a Comment