• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

What is a Class in Java with Example

February 10, 2016 by javainterviewpoint Leave a Comment

A Class can be defined as a template / blueprint for creating objects which defines its state and behavior. Class can have three major components such as variables,methods and constructors. We can create a class with all of these components or some of these or even none of these, but a class with no components is of no use. Lets take a look into the exo-skeleton of declaring a class first

Class in Java syntax:

 <<Access Specifier>> class <<Class Name>> extends
 <<Super Class Name>> implements <<Interface Name>>{}
  • Access specifier : Allowable Access specifier for a class are public and default. Access specifiers defines the range of a class where it can be accessed. If a class is public then it can be accessed from anywhere. If you have not added anything in front of a class then it is called as default access specifier. Default access falls between protected and private access, allowing only classes in the same package to access.
  • class keyword : The access specifier is followed by class keyword which symbolizes that this entity is a class.
  • Class Name : The class keyword is followed by a class name, which follows the rules of identifiers
  • Extending & Implement : A class can extends only 1 other class, whereas it can implement any number of interfaces.

Rules for declaring a class in Java

  1. A class can have only public or default access specifier, no other access specifier ( protected, private) can be applied to a class.
  2. default access can be seen only by classes within the same package
  3. Only abstract, static, final non-access modifiers can be applied to a class.
  4. An abstract class in Java can not be instantiated. It can have both abstract methods and concrete methods
  5. A final class in Java can not be sub-classed but object can be created for it.
  6. It must have the class keyword, and class must be followed by a legal identifier.
  7. All classes will be by default extending Java Object class( java.lang.Object ), in addition to it all the classes can extends one other class ( only one class ).
  8. It can implement any number of java interfaces each interface has to be separated by a comma.
  9. All the variables, methods, and constructors should be defined within the java class only.
  10. Each .java source file may contain only one public class. and can have any number of other visible classes.
  11. The source file name must match the public class name and it must have a .java suffix.

Variables in a class : 

A class can have the following variable types inside it.

  • Local Variables : Local Variables are the variables which are defined within the methods or constructors. Those type of variables will be initialized with in the method and will get destroyed once the execution of the method is completed.
public class Class_Example 
{
    public Class_Example() 
    {
        String value = "Test";// Local Variable inside a Constructor
    }

    public void disp() 
    {
        String name = "JavaInterviewPoint";// Local variable inside method
        System.out.println("Welcome " + name + "!!!");
    }
}
  • Instance Variables : Instance Variables are the one which is defined outside of methods or constructors. These variables get initialized when the class is instantiated and can be called only with the help of objects. These variables can be accessed within any method or constructor.
public class Class_Example 
{
    String name = "JavaInterviewPoint";//Defining a Instance Variable
    public Class_Example() 
    {
        //Using the Instance variable inside a constructor
        System.out.println("Welcome " + name + "!!!");
    }

    public void disp() 
    {
        //Using the Instance variable inside a method
        System.out.println("Welcome " + name + "!!!");
    }
}
  • Class Variables : Class Variables is almost similar to Instance variable except it has a static keyword in the front indicating the variable belongs to the java class and not to any instance. A class variable can be called directly with the class name like <<Class Name>>.<<Variable Name>>
public class Class_Example 
{
    static String name = "JavaInterviewPoint";//Defining a Class Variable
    public Class_Example() 
    {
        //Using the Class variable inside a constructor
        System.out.println("Welcome " + Class_Example.name + "!!!");
    }

    public void disp() 
    {
        //Using the Instance variable inside a method
        System.out.println("Welcome " + Class_Example.name + "!!!");
    }
}

Java class Constructor :

This is the second most important topic which comes into mind when we speak about a class. Every class will be having a constructor either we have to define it explicitly or the compiler will create a default constructor for you. A class can have any number of constructors. Every time when a new instance is created for the class the constructor will be called, the main rule here is that constructor name for a java class should be the same name of the class name and should not have any return type.

public class Class_Example 
{
    static String name = "JavaInterviewPoint";//Defining a Class Variable
    //Default Constructor
    public Class_Example() 
    {
        
    }
    //Parameterized Constructor
    public Class_Example(String name) 
    {
        this.name=name;
    }
}

Example of Class in Java

Lets create a real world example class “BMWCar” putting all the above learnt concepts.

We have a “Vehicle” interface which consist of two methods numberOfWheels() and speedOfVehicle() both will be declared here and the body will be given by BMWCar class.

“Car” is our super class here consisting of a simple carColor() method, the Car class will be extended by our BMWCar class.

Finally “BMWCar” class extends the “Car” class and implements “Vehicle” interface. In the main method we will be creating the object for the BMWCar and will be calling the individual methods.

public interface Vehicle 
{
    public void numberOfWheels();
    public void speedOfVehcile();
}
class car
{
    public void carColor()
    {
        System.out.println("Color of the car is \"Blue\"");
    }
}
public class BMWCar extends car implements Vehicle 
{
    int wheels = 4;//instance variable
    
    public BMWCar()
    {
        System.out.println("Default Constructor called");
    }
    @Override
    public void numberOfWheels() 
    {
        System.out.println("BMW Car has \""+wheels+"\"  wheels");
    }
    @Override
    public void speedOfVehcile() 
    {
        int speed = 50;//local variable
        System.out.println("BMW car is driving at \""+speed+"\" kmph");
    }
    public static void main(String args[])
    {
        //creating object for the child class
        BMWCar bmwCar = new BMWCar();
        //Calling parent class method
        bmwCar.carColor();
        //Calling child class methods
        bmwCar.numberOfWheels();
        bmwCar.speedOfVehcile();
    }
}

Output :

Default Constructor called
Color of the car is "Blue"
BMW Car has "4"  wheels
BMW car is driving at "50" kmph

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?

Filed Under: Core Java, Java Tagged With: Class in Java, Class in Java with Example, Java Class

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·