Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Classes and Methods in Java

In today’s article we will learn about Classes and Methods which are the core concept of Java.

Every Programming Language has its own structure. Java is a programming language, and java has its own structure. Classes and Methods are the core part of any object oriented programming language. We can say java’s core part is the class. Class is the first essential element that must be used during the development of any java program. We can say class is the logical structure on which java is built. Class express nature and shape of the Object.

Class

Whatever code you want, you must write that code inside a class. So now we are familiar with the class and its needs in java programming.

In java, the class that has main() method is said to be the main class. Java compiler starts the execution of code from the main method. Java has so many built-in data types and user can create his/her own data type or structure using classes. We can say that class in java is a template for an object. The object of any class is an instance of a class.

When you are going to define a new class, first you define the nature of the class and what data it will hold.

Every class should contain methods and data. Here we consider methods as operations.. To define class in java we use the class keyword.

Since java is a case sensitive programming language , you must keep in mind that the class keyword needs to be in small case otherwise it will create an error. The simple type of class can be declared like this.

Syntax:

[Access Specifier] class [Class Name]

{

// constructor

// Declaration of variables .

// Declaration of Methods

}

In the above syntax we examine that access specifier specifies the scope of class and it not compulsory. You can write access specifier as per your need. class is a keyword used for define new class. And then class name is the name of your class. Keep one thing in mind, this is Java naming convention. In java class name first letter must need to be in Upper case.

Example:

class SimpleClass
  {
  //body of your class;
  }

Here we see a simple declaration of a class in Java.

After looking at a simple class, now we are going to learn some complex class declarations.

Syntax:

[ Access Specifier ] class ClassName [extends ClassName] [implements InterfaceName1,Interfacename2,.....,InterFacenameN]

{

[ Access Specifier ] [datatype] mebmerVariable1;

[ Access Specifier ] [datatype] mebmerVariable2;

.......

.......

[ Access Specifier ] [datatype] mebmerVariableN;

// initializer block in java to initialize any class members..

{

//Statements1;

//Statements2;

.......

//StatementsN;

}

// static block in java only static member

static

{

/*

* This block is use For Only Static Variables and methods we can not access non static

* dataMembers and Methods in this block

*/

}

/* Constructor In Class

* Access Specifier Must be public or default other wise there is no use of constructor.

* And Constructor Never Return Any Value.

* */

[ Access Specifier ] Constructor1();

{


//Statements1;

//Statements2;

....

//StatementsN;

}

[ Access Specifier ] Constructor2(Parameter List);

{


//Statements1;

//Statements2;

....

//StatementsN;

}

....

....

[ Access Specifier ] ConstructorN(Parameter List);

{

//Statements1;

//Statements2;

....

//StatementsN;

}


// Methods of Class in the Java

[ Access Specifier ] [return datatype] methodName1()

{

//Statements1;

//Statements2;

....

//StatementsN;


}

[ Access Specifier ] [return datatype] methodName2(Parameter List)

{

//Statements1;

//Statements2;

....

//StatementsN;

}

...

...

[ Access Specifier ] [return datatype] methodNameN(Parameter List)

{

//Statements1;

//Statements2;

....

//StatementsN;

}

}

Detail Description of above syntax

In first line we see Access specifier that specifies the scope of the class. There are mainly 4 kind of access specifiers in java: private, protected, public and default. If you do not specify any specifier to the class then it would be default. That can only be accessible in current project.

Next we use class keyword to define class. Class name is a name of your class that you want to create. Next we find another keyword that is extends. This keyword is used only when you are using the concept of inheritance. We can extend one class in our class. You need to specify your class name that you want to inherit after the keyword extends. Next keyword we find in syntax is implements. This keyword is similar to extends but different in that extends keyword is used to inherit a class while implements keyword is used to inherit an interface. We can not inherit more than one class in java but we can inherit more than one interface in our class. As by using interface we achieve multiple inheritance in java. We can define multiple constructors of class. A class has by default constructor without parameter. We can define constructor with parameter and also we can override the constructor in java.

Next in syntax after defining a class we are defining class members, initializer block, static block.

Class member contain variables and methods.

Initializer block in java

Initializer block is called when new object is created or we allocate the memory to object. That block is called before the constructor call and it is very useful when we have multiple constructors in a class and we need to use same content in the entire constructor. At that time we use the initializer block in our class.

Static block in java

Static block is called when Class is loaded in memory the first time. It is called only one time when we load the class. We can declare static block in java by using simply static keyword. Static block is called first in the class.

Syntax:

static

{

// your code that you want to execute when the object of class is created .

//we can initialize the static member in this block .we can not use non static member in this block.

}

The variable or data that we define inside the class are known as instance variables. We can simply say that anything that is defined inside the class such as methods and variables are commonly known as members of the class. We define object of class to access the class members. Every object of a class has a new copy of variables and methods of class. For an example, when there are two objects one and two, then these objects have different Memory allocation and different copy of every variables of class. When we are declaring new class, we are actually creating new data type. After declaring class we are going to create the object of that class.

To define an object of class is as easy as declaring variables. Same like variables first we define an object and after defining object we initialize it using new operator and allocate memory to class object. After defining object and allocating memory to it now object of class can access all the variables and methods that are declared in its class.

Simple form of declaring object of a class is like below:

Syntax:

[Class Name] object name= new [Class Name];

Here in above syntax we declare and initialize new object using new operator.

Example:

  SimpleClass newObject=new SimpleClass();

Here in above Example we simply define newObject of SimpleClass using new Operator.

Now newObject has all the variables and methods of SimpleClass.

One thing that noticeable is when we are declaring integer or character type variable we do not need to use new operator but when we are declaring objects of a class, it is necessary to use new operator. The actual reason behind that is in java primitive data types such as integer, float and character are not implemented like objects,. They are implemented as normal variables instead.

We can assign object to another object. By doing that we assigning same copy of one object to another.

For an example:

  SimpleClass object1=new SimpleClass();
  SimpleClass object2=object1;

In above example we see that object1 is created using new operator and object2 has assigned object1. After doing this type of assignment now both object object1 and object2 refer to the same object.

By doing this type of assignment we are not making copy of an object but actually we are creating cope of reference.

In java we find variance in classes. Some different kind of classes in java are:

  1. Abstract Class.
  2. Static Class.
  3. Final Class.
  1. Abstract Class:We can define abstract class in java using abstract keyword. The object of an abstract class can not be created.
    Any class in java that has method with abstract keyword then that class must be an abstract class. Any class that inherits from an abstract class must define all the abstract methods of that class, otherwise it will cause an error. The class that inherit abstract class and not define method of abstract class then we have to make that class abstract class.
  2. Static Class:We can define static class in java using static keyword. As we define method and variable static we can also define static class. The class that is written inside the class is known as nested class. Keep in mind that during static class declaration, we cannot make outer class static. We can only make inner class static.
  3. Final Class:final keyword is referred to constant in java. As we define final variable and final method, We can also define final class in java. final is a keyword that is used to define final class. Final class in java can not be inherited and can not be subclassed. If you try to inherit final class in java then it will show you compile time error. There are so many benefits of final classes.

Final classes in java improve performance of your application. JVM and application can cache final classes. So many people make mistakes in understanding final and finally. Final is totally different from finally. Finally keyword in java is used for exception handling while final is used for constant type.

Methods In java

Methods in java provide operation to the class and its variable. The common example of method that we have already seen is main() method. Main method in java is an entry point of program. Compiler starts theprogram execution from the main method. As we can see, the main method is a static method.

Same like class method has access specifier that specifies the scope of methods, a method can be static. Astatic method can be directly called by its class name. We can not call static method using object of that class. A method can also be final. Another example of method that we used in java is finalize() method. finalize() method is used to perform some action before destroying an object.

We can overload method in java. Method overloading concept shows that we can define more than one method with the same name but with different signature. For an example display() method that take no parameters and display(String s) that take one parameters. Here we can say method overloading is taking place.

Methods play an important role in java. As all the code execution and its handling can be done using methods.

Here below example shows the above listed concepts with description.

Listing 1: SimpleClassExample.java

  /*   This is a simple class Example with an overloaded 
   *             Constructor and Overloaded Methods
   */
   
  class Article
  {
                  /* 
                   * Here We declare our Member variable or we can say that the 
                   * instance variable of the class.
                   */
                  
                  private int articleId; 
                  private String articleName;
                  private String articleAuthor;
                  private float price;    
                  private float tax;
                  public static int totalArticle;
                  
                  /*
                   * Here, We initialize the value of static member variable using the static block.
                   * And we can not use the non-static variable inside this block.
                   */
                   
                  static 
                  {
                                 System.out.println("\n This is a Static Block it call first and Only One Time \n");
                                 totalArticle=0;
                  }
                  
                  /*
                   * Here, We initialize the value of member variable using the initializer block.
                   * This bloc is called whenever Class is created.
                   * This block is useful when we use same member variable are needed to be initialized in all the Constructord 
                   */
                   
                  {
                                 System.out.println("\n This is a Initializer Block it call after static block and before constructor\n");
                                 price=0.0f;
                                 tax=12.0f;
                  }
                  
                                 
                  /* 
                   * Here we Create a Constructor of class.
                   * if we do not create any constructor, the given one is called a default constructor of the class.
                   * Constructor is called when we create a new Object of Particular Class
                   */
                  
                  public Article()
                  { 
                                 System.out.println("This is A simple constructor of class without Any Arguments");
                                 articleId=++totalArticle;
                                 articleName=null;
                                 articleAuthor=null;
                  }
                  
                  public Article(String articleName)
                  { 
                                 System.out.println("This is A constructor of class with one Arguments");
                                 this.articleId=++totalArticle;
                                 this.articleName=articleName;
                                 this.articleAuthor=null;
                  }
                  
                  public Article(String articleName,String articleAuthor)
                  { 
                                 System.out.println("This is A constructor of class with two Arguments");
                                 this.articleId=++totalArticle;
                                 this.articleName=articleName;
                                 this.articleAuthor=articleAuthor;
                  }
                  
                  public Article(String articleName,String articleAuthor,float price)
                  { 
                                 System.out.println("This is A constructor of class with two Arguments");
                                 this.articleId=++totalArticle;
                                 this.articleName=articleName;
                                 this.articleAuthor=articleAuthor;
                                 this.price=price;
                  }              
                                 
                  /*
                   *  Methods of Class 
                   */
                  
                  public int getArticleId()
                  {
                                 return articleId;
                  }
                  
                  /* Get and Set Method For articleName */
                  
                  public void setArticleName(String articleName)
                  {
                                 this.articleName=articleName;
                  }
                  public String getArticleName()
                  {
                                 return this.articleName;
                  }
                  
                  /* Get and Set Method For articleAuthor */
                  public void setArticleAuthor(String articleAuthor)
                  {
                                 this.articleAuthor=articleAuthor;
                  }
                  public String getArticleAuthor()
                  {
                                 return this.articleAuthor;
                  }
                  
                  /* Get and Set Method For article price to get and set the price of article */
                  public void setPrice(float price)
                  {
                                 this.price=price;
                  }
                  public float getPrice()
                  {
                                 return this.price;
                  }
                  
                  /* Get and Set Method For article tax */
                  public void setTax(float tax)
                  {
                                 this.tax=tax;
                  }
                  public float getTax()
                  {
                                 return this.tax;
                  }
                  
                  /* This is a static method. It is accessed  directly by Class Name. We do not need to create an object to call the method*/
                  public static int getTotalArticle()
                  {
                                 return totalArticle;
                  }
                  
                  /* Here it is an overloaded Method of Class That Returns Netprice of Article */
                  
                  public float getNetPrice()
                  {
                                 return getPrice()+(getPrice()*getTax()/100);
                  }
                  public float getNetPrice(int qty)
                  {
                                 return (qty*getPrice())+(qty*getPrice()*getTax()/100);
                  }
  }
   
   
  public class SimpleClassExample
  {
                  static 
                  {
                                 System.out.println("This is a Static Block of Main Class");            
                  }
      public SimpleClassExample() 
      {
                                 
      }
         
      public static void main(String[] args) 
      {
                  Article article=new Article();  //This Method Call Default Constructor.
                  article.setArticleName("Article - 1");
                  article.setArticleAuthor("Author -1 ");
                  article.setPrice(299f);
                  
                  System.out.println("Article Id    ::" + article.getArticleId());
                  System.out.println("Article Name  ::" + article.getArticleName());
                  System.out.println("Author Name   ::" +article.getArticleAuthor());
                  System.out.println("price         ::"+article.getPrice());
                  System.out.println("price with TAX:"+article.getNetPrice());
                  
                  article=new Article("Article - 2","Author -2 "); // here this constructor with 2 argument.
                  article.setPrice(299f);
                  
                  System.out.println("Article Id    ::" + article.getArticleId());
                  System.out.println("Article Name  ::" + article.getArticleName());
                  System.out.println("Author Name   ::" +article.getArticleAuthor());
                  System.out.println("price         ::"+article.getPrice());
                  System.out.println("price with TAX(10 Item):"+article.getNetPrice(10));
                  
                  article=new Article("Article - 3","Author -3 ",329f); // Constructor with 3 argument.
                  
                  System.out.println("Article Id    ::" + article.getArticleId());
                  System.out.println("Article Name  ::" + article.getArticleName());
                  System.out.println("Author Name   ::" +article.getArticleAuthor());
                  System.out.println("price         ::"+article.getPrice());
                  System.out.println("price with TAX(10 Item):"+article.getNetPrice(10));
                  
                  System.out.println("====================================================================");
                  System.out.println("Total Number of Article ::"+ Article.getTotalArticle());
      }
  }

Output Listing 1: SimpleClassExample.java

This is a Static Block of Main Class

This is a Static Block it call first and Only One Time

This is a Initializer Block it call after static block and before constructor

This is A simple constructor of class without Any Arguments

Article Id :1

Article Name :Article - 1

Author Name :Author -1

price :299.0

price with TAX:334.88

This is a Initializer Block it call after static block and before constructor

This is A constructor of class with two Arguments

Article Id :2

Article Name :Article - 2

Author Name :Author -2

price :299.0

price with TAX(10 Item):3348.8

This is a Initializer Block it call after static block and before constructor

This is A constructor of class with two Arguments

Article Id :3

Article Name :Article - 3

Author Name :Author -3

price :329.0

price with TAX(10 Item):3684.8

====================================================================

Total Number of Article:3

The above example illustrates the use of class and constructors and methods. Here in this example we use static blocks to initialize members. We notice that static blocks that we write execute only once when we load the class first time. Here Article class has 4 constructors this concept demonstrates the use of constructor overloading.

Conclusion

Here in this article we learn the use of class and methods in java. We also learned how the class is defined and different types of classes in java. We got the idea to implement classes in different way. Basically we learned about the core part of the Java program.



Computer system engineer who has 4 year of experience in the field our web-development ,FPGA, and java programming.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login