Tuesday, August 10, 2021

How to use Class in Java Programming - Example

When I first about Class in Java I just thought what is this Class in Java and from that date to now Whenever we talk about java its really incomplete without classes, every one who are little bit familiar with java knows it’s purely object oriented language means every thing we discuss in java as object .so its very important for learner or anyone who is keen to know about java should know about java class then only they can move forward on java world.
In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class including members, field and method.


If you have just started programming in Java or learning Please check my article How to Set Path for Java and How to set ClassPath for Java covering two important concept PATH and CLASSPATH.



How to use Class in Java Programming Example



1. What is a Java Class?

Java class is nothing but a template for the object you are going to create or it’s a blueprint by using this we create an object. In simple word, we can say it’s a specification or a pattern which we define and every object we define will follow that pattern.






2. What does Java Class Consist

§     When we create a class in java the first step is keyword class and then name of the class or identifier we can say.
§          Next is class body which starts with curly braces {} and between this all things related with that class means their property and method will come here.



Template is:


Class (name of the class) {

(Here define member of class)

}

Access level of class:


Java class has mainly two type of access level:

Default: class objects are accessible only inside the package.

Public: class objects are accessible in code in any package.



What are members of Class?

When we create a class its totally incomplete without defining any member of this class same like we can understand one family is incomplete if they have no members.
What is Class in Java Program with Example
Field: field is nothing but the property of the class or object which we are going to create .for example if we are creating a class called computer then they have property like model, mem_size, hd_size, os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of the class.
Each field and method has an access level:
  • private: accessible only in this class
  • package or default: accessible only in this package
  • protected: accessible only in this package and in all subclasses of this class
  • public: accessible everywhere this class is available

A real-world example of Class in Java Programming:

In the real world, if we want to understand the class everything of the same quality can be visualized as a class e.g. men, women,birds , bicycles ,cars or  we can say vehicle .

The entire vehicle will make one class they have the property like no_of_wheels, color, model, brand etc. Now we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method on that class.

Similarly, all human being also can be one class now their member will be a men,women ,child.,isAlive() ,isDeath() can be their method or behavior of that class .

Again we can make Men or women a separate class and define their property and method accordingly. In short in java every problem we get a solution can think in terms of class and object.


One Java class example:

Class Stock {
Public commodity;
Public price;
Public void buy (int no_of commodity) {}
Public boolean sale () {}
}

In this example Stock is called Class and commodity, price are field and buy() and sale() are two methods defined inside class. To access elements of Class you need to create an instance of class Stock. You can create instance of Class using keyword new as shown below

Stock highBetaStock = new Stock();

For calling method of Stock just call by using instance.

highBetaStock.buy(1000);
highBetaStock.sell();



In short in java everything must be thinking in terms of java class its nothing but a template they have their own members and methods for accessing those members. The entire member has their own visibility which is decided by the developer where they want to use those objects.


Related Java Tutorials

11 comments:

  1. Hi Gokul, to write a Java program without main is not difficult , you can write any Class but if you want to execute them in put the code inside Static block and it will run when class will be loaded in JVM.

    ReplyDelete
  2. I have just started learning Java and was puzzled with what is Class in Java, since I came from C background I only familiar with Structure in C which doesn't contain method but here Java Class can contain both method or function and field. Thanks you clear my doubt on Class. please write on Object as well.

    ReplyDelete
  3. I have some questions on Class in Java:
    Can one Class contain another Class in Java ?
    Can same Class stay in two different package in Java ?
    Can same method exits in two different Class in Java?
    What time Class is loaded in Program , is it during compile time by invoking javac or runtime when you invoke java.
    How many Class a Class can extend in Java ?
    What is abstract Class in Java ?
    What is nested Static Class in Java?
    What is System class in Java ?
    How does Class relates to ClassLoader in Java ?
    Can we instruct that a paritcular Class must be loaded by one Class loader ?

    ReplyDelete
  4. Some more questions on Class in Java
    What is wrapper Class ? any example
    What is final Class in Java? any example
    What is immutable Class in Java ? any example
    What is Thread-Safe Class in Java ? any example

    Cheers :)

    ReplyDelete
  5. Can anyone type that programs for me, I am having great difficulty. I would really appreciate that.

    1) Display calendars in a message dialog box. Since the output is generated from several static methods in the class, you may define a static String variable output for storing the output and display it in a message dialog box.

    The Account class. Design a class named Account that contains:
    • A private int data field named id for the account (default 0)
    • A private double data field named balance for the account (default 0)
    • A private double data field named annualInterestRare that stores the current interest rate (default 0). Assume all accounts have the same interest rate.
    • A private Date data filed named dateCreated that stores the date when the account was created.
    • A no-arg constructor that creates a default account.
    • A constructor that creates an account with the specified id and initial balance.
    • The accessor and mutator methods for id, balance, and annualInterestRate.
    • The accessor method for dateCreated
    • A method named getMonthlyInterestRate() that returns the monthly interest rate
    • A method named withdraw that withdraws a specified amount from the account.
    • A method named deposit that deposits a specified amount to the account.

    Draw the UML diagram for the class. Implement the class. Write a program that creates an Account object with an account ID of 1122, a balance of €20,000, and annual interest rate of 4.55. Use the withdraw method to withdraw €2,500, use the deposit method to deposit €3,000 and print the balance, the monthly interest, and the date when this account was created.

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

    2) ATM Machine. Use the Account class you created in Assignment one to simulate an ATM machine.
    Create 10 accounts in an array with id 0,1,.........9, and initial balance of €50. The system prompts the user to enter an id. If the id is entered incorrectly ask the user to enter a correct id. Once the id is accepted the main menu is displayed as shown in the sample run. You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money and 4 for exiting the main menu.
    If the user tries to withdraw more money than is available the program reports a “ Not enough funds” message. Once you exit the system will prompt for an id again. So once the system starts, it will not stop.

    Enter an id: 3

    Main menu
    1: check balance
    2: withdraw
    3: deposit
    4: exit
    Enter a choice: 1
    The balance is 50.0


    Main menu
    1: check balance
    2: withdraw
    3: deposit
    4: exit
    Enter a choice: 2
    Enter an amount to withdraw: 25


    Main menu
    1: check balance
    2: withdraw
    3: deposit
    4: exit
    Enter a choice: 1
    The balance is 25.0

    ReplyDelete
  6. in a form we call doget to one sevlet.but that servlet override the doget,dopost and service()methods.. so which method is executed ?
    ........my doubt is doget,dopost coming under service()method ..but we call doget..first reuest is going to service() method or doget()...please tell me answer

    ReplyDelete
  7. @Anonymous when request will come Container will do its job regarding creating headers etc and than call service() method. if you are extending HttpServlet than its service() method call doGet() if request type is GET and doPost() if request type is POST.

    ReplyDelete
  8. Hi Hans, are you talking about capital case class and public modifiers, well those are somehow turned in capital case.

    ReplyDelete
  9. Class is finite state automaton

    ReplyDelete
  10. can u give simple program on based the concepts like class,object,data abstraction,data encapsulation,inheritance,polymorphism,dynamic binding,message passing

    ReplyDelete