Wednesday 5 February 2014

Declaring a class

class in java declared with a keyword “class”

    Syntax
    class ClassName{
    }

   Example
    class Person{
    }

How to declare properties of a class
  Each property is represented by a variable.

class Person{
 float height, weight;
 String color, country;
}

Since height and weight are real type values, so these are declared as a float. Where as color and country are of type String. So these are declared as type string.

Note:
   We haven't discussed anything about strings, just note that string a group of characters.

How to define behaviors for a class
   Each behaviour in Java represented by a method.

   Method is a block of statements, with a name associated with it.
      Syntax:
         returnType methodName(parameters){

         }
      Example
         int sum(int a, int b){
            return (a+b);
         }

      here,
         returnType is int
         parameters are a, b.

return value must match with the return type of the method.
After adding the behaviors for the class Person, code changed like below
class Person{
 float height, weight;
 String color, country;

 float getHeight(){
  return height;
 }

 float getWeight(){
  return weight;
 }

 String getColor(){
  return color;
 }

 String getCountry(){
  return country;
 }
}



Classes & Objects                                                 Object Creation                                                 Home

No comments:

Post a Comment