Showing posts with label Java OOPS. Show all posts
Showing posts with label Java OOPS. Show all posts

Thursday, April 4, 2024

Method Overriding in Java

In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding in Java.

Rules for method overriding in Java

  1. Overridden method must have the same name and same number and type of parameters in both parent and child classes.
  2. In the case of parent-child relationship if two classes have the method with same name and signature then only it is considered as method overriding, otherwise it is method overloading.
  3. The visibility of access modifier can't be reduced in the child class method. For example if the method is protected in the parent class then the overridden child class method can have the modifier as public (visibility can be increased) but not as private (reduced visibility).
  4. In case of method overriding, return type of the child class method should be of the same type or the sub type of the parent class' method return type. Read more about it in this post- Covariant Return Type in Java
  5. Java exception handling has certain rules in place for method overriding.
    If parent class method doesn't throw any exception then the child class method can throw only unchecked (runtime) exceptions not checked exceptions.
    If parent class method throws an exception then the child class method can throw the same exception, subtype exception of the exception declared in the superclass method or no exception at all.
    Read more about rules regarding method overriding with respect to exception handling in this post- Java Exception Handling And Method Overriding

Method overriding in Java Example

In the example there is a super class Parent and a sub-class Child. In the super class there is a method dispayData() which is overridden in the sub-class to provide sub-class specific implementation.

class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overridden Method
 public void dispayData(){
  System.out.println("Value of j " + j);
 } 
}

public class OverrideDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child child = new Child(5, 7);
  child.dispayData();  
 }
}

Output

Value of j 7

It can be noticed here that when displayData() is invoked on an object of class Child, the overridden displayData() method of the child class is called.

Benefits of method overriding in Java

Method overriding allows java to support run-time polymorphism which in turn helps in writing more robust code and code reuse.

Method overriding also helps in hierarchical ordering where we can move from general to specific.

If we use the same example to demonstrate run time polymorphism here.
class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overridden Method
 public void dispayData(){
  System.out.println("Value of j " + j);
 } 
}

public class OverrideDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child child = new Child(5, 7);
  Parent parent = new Parent(8);
  // calling parent displayData method
  parent.dispayData();
  // parent holding the reference of child
  parent = child;
  // child class displayData method will be called
  parent.dispayData();  
 }

}

Output

Value of i 8
Value of j 7

It can be noticed here that initially parent object calls displayData() method of parent class, later at run time the reference is changed and the parent is assigned the reference of child class. Now, when the displayData() method is called on the parent object, it calls the overridden method of the class Child.

Points to note-

  • If method in the sub-class has the same name and signature as the parent class method then only it is called method overriding otherwise it is method overloading.
  • Method overriding allows java to support run-time polymorphism.
  • Method overriding helps in hierarchical ordering where we can move from general to specific. In super class a method can have a general implementation where as the sub classes provide the more specific implementation by overriding the parent class method.
  • If a method is declared as final in parent class then it can not be overridden by sub classes.
  • If a method is declared as abstract in the parent class then the sub class has to provide implementation for those inherited abstract methods

That's all for this topic Method Overriding in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Method Overloading in Java
  2. Inheritance in Java
  3. Abstraction in Java
  4. Java Exception Handling And Method Overriding
  5. Java OOP Interview Questions And Answers

You may also like-

  1. finalize method in Java
  2. Association, Aggregation and Composition in Java
  3. Why main Method static in Java
  4. Varargs (Variable-length Arguments) in Java
  5. How to read input from console in Java?
  6. Difference Between sleep And wait in Java Multi-Threading
  7. Race condition in Java multi-threading
  8. How to Loop or Iterate an Arraylist in Java

Wednesday, April 6, 2022

Java Abstract Class and Abstract Method

An abstract class in Java is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods along with methods with implementations.

The declaration of an abstract method starts with the abstract keyword and ends with a semicolon, it does not have a method body.

General form of abstract method in Java

abstract type method_Name(parameter_list);

If a class contains an abstract method, either declared or inherited from another class, it must be declared as an abstract class.

Note that a class with all its methods implemented can also be declared as abstract. But declaring the class as abstract is mandatory if there is any abstract method in a class.


Usage of Abstract class in Java

There are scenarios when you would want to define a generalized structure using a super class without providing a complete implementation of every method. In that case sub classes have the responsibility to provide implementation for the methods.

In such scenario where base class just provides the general template and the sub-classes provide the specific implementation, base class can be defined as an abstract class with implementation for methods that are common for the sub-classes. Methods for which implementation varies are marked as abstract methods in the base class thus leaving it to the sub-classes to provide implementation for such methods.

Restrictions with Abstract Classes in Java

  • Any class that contains one or more abstract methods must also be declared abstract.
  • Abstract class can not be directly instantiated so there can't be any object of an abstract class.
  • Any class that extends an abstract class must provide implementation of all the abstract methods in the super class; otherwise the sub-class must be declared abstract itself.
  • There can't be an abstract constructor or abstract static method.

Java Abstract class Example

Let's say we have an abstract class Shape which defines the general structure for the 2D figures and declares area method which is abstract. That would mean any sub-class extending the super class Shape has to provide an implementation of meaningful area method.

abstract class Shape{
 double length;
 double breadth;
 //Constructor
 Shape(double length, double breadth){
  this.length = length;
  this.breadth = breadth;
 }
 // common method
 public String getFigureType(){
  return "2D figure";
 }
 // Abstract method
 abstract void area();
}

class Triangle extends Shape{
 //constructor to initialize length
 Triangle(double i, double j){
  super(i, j); // calling the super class constructor  
 }
 // Abstract method implementation for Triangle class
 void area(){
  System.out.println("In area method of Triangle");
  System.out.println("Area of Triangle - " + (length * breadth)/2);
 }
}

class Rectangle extends Shape{
 //constructor to initialize length
 Rectangle(double i, double j){
  super(i, j); 
 }
 // Abstract method implementation for Rectangle class
 void area(){
  System.out.println("In area method of Rectangle");
  System.out.println("Area of Rectangle - " + length * breadth);
 }
}

In the above program you can see that the abstract class Shape provides a generalized structure for the 2D figures. There are two fields with in the Shape class representing 2D figure. These two fields can be used to initialize length and breadth of the figure (in case of Rectangle) or the base and height of the figure (in case of Triangle). Since the abstract class Shape is for 2D figure so method getFigureType() will always return same value "2D figure" for any subclass so it is placed with in the abstract class to be used by all the sub classes.

How area is calculated depends on the figure that is why it is declared as abstract in the Shape class so that the class extending the Shape class can provide the appropriate implementation of the area method.

Java Abstract class and run time polymorphism

As we already know there can't be an object of an abstract class, but abstract class can be used to create object references.

We have also seen that abstract class is deigned to be used as a super class with generalized structure. Since run time polymorphism in Java is implemented through the use of super class reference thus it is obvious that abstract class reference (super class reference) could be used to refer to subclass object.

Run time polymorphism with Abstract class Example

If we take the same Shape class as used above
abstract class Shape{
 double length;
 double breadth;
 //Constructor
 Shape(double length, double breadth){
  this.length = length;
  this.breadth = breadth;
 }
 // Abstract method
 abstract void area();
 
}

class Triangle extends Shape{
 //constructor to initialize length
 Triangle(double i, double j){
  super(i, j); // calling the super class constructor  
 }
 // Abstract method implementation for Triangle class
 void area(){
  System.out.println("In area method of Triangle");
  System.out.println("Area of Triangle - " + (length * breadth)/2);
 }
}

class Rectangle extends Shape{
 //constructor to initialize length
 Rectangle(double i, double j){
  super(i, j); 
 }
 // Abstract method implementation for Rectangle class
 void area(){
  System.out.println("In area method of Rectangle");
  System.out.println("Area of Rectangle - " + length * breadth);;
 }
}

public class PolymorphicTest {
 public static void main(String[] args){
  // Abstract class reference
  Shape shape;
  Triangle triangle = new Triangle(5, 6); 
  Rectangle rectangle = new Rectangle(7, 5); 
  // shape dynamically bound to the Triangle object
  shape = triangle;
  // area method of the triangle called
  shape.area(); 
   // shape dynamically bound to the Rectangle object
  shape = rectangle;
  // area method of the rectangle called 
  shape.area(); 
 }
}

Output

In area method of Triangle
Area of Triangle - 15.0
In area method of Rectangle
Area of Rectangle - 35.0

It can be seen that a reference of an abstract class is created

Shape shape;

That shape reference refers to the object of Triangle class at run time first and then object of Rectangle class and appropriate area method is called.

Abstract class in Java with interfaces

If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.

public interface MyInterface {
 void method1();
 String method2(String Id);
}
abstract class in Java
Error if all methods of interface are not implemented

But we can declare the class as abstract in that case

public abstract class AbstractClassDemo implements MyInterface {
 public static void main(String[] args) {
  System.out.println();
 }
}

Points to note-

  • There can be a class declared as abstract that provides implementation of all the methods in a class i.e. no abstract method in the class but vice versa is not true, if there is any abstract method in a class then the class must be declared abstract.
  • Abstract class in Java may have some methods with implementation and some methods as abstract.
  • Abstract classes can not be instantiated to create an object.
  • An object reference of an abstract class can be created.
  • If a class implements an interface and does not provide implementation for all the interface methods, it must be declared abstract.

That's all for this topic Java Abstract Class and Abstract Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Difference Between Abstract Class And Interface in Java
  2. Inheritance in Java
  3. Polymorphism in Java
  4. final Keyword in Java With Examples
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Marker interface in Java
  2. Type Casting in Java With Conversion Examples
  3. static block in Java
  4. Creating Custom Exception Class in Java
  5. Multi-Catch Statement in Java Exception Handling
  6. How and Why to Synchronize ArrayList in Java
  7. Java CyclicBarrier With Examples
  8. Deadlock in Java Multi-Threading

Tuesday, May 18, 2021

Java OOP Interview Questions And Answers

In this post some of the Java OOP interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is encapsulation?

    Encapsulation means keeping together the implementation (code) and the data it manipulates (variables). In Java a class contains the member variables (instance variables) and the code in methods. In a properly encapsulated Java class method defines how member variables can be used.
    Read more about encapsulation here.


  2. What is abstraction?

    Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, Abstraction means abstracting/hiding the real working and we, as a user, knowing only how to use it.

    Real world example would be a vehicle which we drive with out caring or knowing what all is going underneath.

    Read more about abstraction here.


  3. Difference between abstraction and encapsulation?

    Abstraction is more about hiding the implementation details. In Java abstraction is achieved through abstract classes and interfaces.

    Encapsulation is about wrapping the implementation (code) and the data it manipulates (variables) with in a same class. A Java class, where all instance variables are private and only the methods with in the class can manipulate those variables, is an example of encapsulated class.
    Read more about difference between Encapsulation and Abstraction in Java here.


  4. What is Polymorphism?

    Polymorphism, a Greek word, where poly means many and morph means change, thus it refers to the ability of an object taking many forms. The concept of polymorphism is often expressed as "One interface, multiple methods".
    Where one general class may have the generic method and the derived classes (classes which extend the general class) may add their own specific method with implementation. At the time of execution "One interface" i.e. the general class will take "many forms" i.e. references of the derived classes.
    Read more about polymorphism here.


  5. What is inheritance?

    Inheritance is a mechanism, by which one class acquires, all the properties and behaviors of another class. The class whose members are inherited is called the Super class (or base class), and the class that inherits those members is called the Sub class (or derived class).
    The relationship between the Super and inherited subclasses is known as IS-A relationship.
    Read more about inheritance here.


  6. What Is a Class?

    In object-oriented terms class provides a blue print for the individual objects created from that class. Once a class is defined it can be used to create objects of that type.
    Read more about class here.


  7. What Is an Object?

    In object-oriented terms object is an instance of the class, which gets its state and related behavior from the class. When a new class is created essentially a new data type is created. This type can be used to declare objects of that type.
    An object stores its state in fields and exposes its behavior through methods.
    Read more about object here.


  8. What is method overloading?

    When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded. This process of overloaded methods is known as method overloading.
    Read more about method overloading here.


  9. What is method overriding?

    In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
    Read more about method overriding here.


  10. What is interface in Java?

    Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
    Interfaces look syntactically similar to classes, but they differ in many ways -

    • Interfaces don't have instance variables.
    • In interfaces methods are declared with out any body. They end with a semicolon.
    • Interface can't be instantiated.
    • Interfaces don't have constructors.
    • An interface is implemented by a class not extended.
    • An interface can extend multiple interfaces.

    Read more about interfaces here.

  11. Can an Interface be final?

    No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.

    Read more about interfaces here.

  12. What is an abstract class?

    An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.

    Read more about abstract class here.

  13. What are the differences between abstract class and interface?

    Abstract Class Interface
    Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
    Note: From Java 8 interfaces can have default methods and static methods.
    Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only.
    Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
    Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods.
    Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor.
    Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
    Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method.
    Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract.
    Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses.


  14. What is an Assocation?

    An association is a structural relationship, in object oriented modelling, that specifies how objects are related to one another. This structural relationship can be shown in-

    • Class diagram associations
    • Use case diagram associations
    An association may exist between objects of different types or between the objects of the same class. An association which connects two classes is called a binary association. If it connects more than two classes (not a very common scenario) it is called n-ary association. There are two types of associations
    • Aggregation
    • Composition

    Read more about Association here.


  15. What is an Aggregation?

    Sometimes you do need to define a “whole/part” relationship between classes where one class (whole) consists of smaller classes (part). This kind of relationship is called aggregation. It is also known as a “has-a” relationship as object of the whole has objects of the part. For example Company has a Person.

    Aggregation doesn't represent a strong "whole/part" relationship and both the "whole" and "part" entities can survive without each other too.

    Read more about Aggregation here.


  16. What is a Composition?

    There is a variation of aggregation called composition which has strong ownership, thus the scope of the whole and part are related. In composition if there are two classes, class A (whole) and class B (part) then destruction of class A object will mean class B object will also cease to exist. Which also means class B object may be a part of class A object only.
    Read more about Composition here.


Related Topics

  1. Core Java Basics Interview Questions And Answers
  2. Java String Interview Questions And Answers
  3. Java Exception Handling Interview Questions And Answers
  4. Java Multithreading Interview Questions And Answers
  5. Java Collections Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Friday, May 14, 2021

Method Overloading in Java

When two or more methods with in the same class or with in the parent-child relationship classes, have the same name but the parameters are different in types or number, the methods are said to be overloaded. This process of overloaded methods is known as method overloading in Java.

Method overloading is one of the ways through which java supports polymorphism. In fact method overloading is an example of static polymorphism or compile time polymorphism.

When an overloaded method is called, which of the overloaded method is to be called is determined through-

  • Types of the parameters- For example test(int a, int b) and test(float a, int b). In these overloaded methods name is same but the types of the method parameters differ.
  • Number of the parameters- For example test(int a, int b) and test(int a, int b, int c). In these overloaded methods name is same but the number of parameters is different.

Please note that return type of the methods may be different but that alone is not sufficient to determine the method that has to be called.


Examples of method overloading in Java

1- Method overloading example with methods having different types of parameters. In the Java example there are two overloaded methods, one having two parameters and both are int where as other method has one int and one double parameter.

public class OverloadingExample {
 // overloaded Method
 void overloadedMethod(int i, int j){
  System.out.println("In overloadedMethod with both int parameters- " + i);
 }
 
 // overloaded Method
 void overloadedMethod(int i, double j){
  System.out.println("In overloadedMethod with int and double parameters " + i + " " + j);
 }
 
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5, 7);
  obj.overloadedMethod(5, 103.78);
 }
}

Output

In overloadedMethod with both int parameters- 5
In overloadedMethod with int and double parameters 5 103.78

2- Method overloading example with methods having different number of parameters. In the Java example there are two overloaded methods, one having a single int parameter where as other method has one int and one String parameter.

public class OverloadingExample {
 // overloaded Method
 void overloadedMethod(int i){
  System.out.println("In overloadedMethod with int parameter- " + i);
 }
 
 // overloaded Method
 void overloadedMethod(int i, String s){
  System.out.println("In overloadedMethod with int and string parameters- " + i + " " + s);
 }
 
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5);
  obj.overloadedMethod(5, "Test");
 }
}

Output

In overloadedMethod with int parameter- 5
In overloadedMethod with int and string parameters- 5 Test

Method overloading in Java and automatic type conversion

In Java, automatic type promotion may happen and it does have a role in how overloaded methods are called, let's see it with an example to have clarity.

public class OverloadingExample {
 // overloaded Method with 1 int param
 void overloadedMethod(int i){
  System.out.println("In overloadedMethod with one int parameter " + i);
 }
 
 // overloaded Method with 2 double params
 void overloadedMethod(double i, double j){
  System.out.println("In overloadedMethod with 2 double parameters " + i + " " + j);
 }
 
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5);
  obj.overloadedMethod(5.7, 103.78);
  obj.overloadedMethod(5, 10);
 }
}

Here notice the third call to the method
obj.overloadedMethod(5, 10);

It has 2 int params, but there is no overloaded method with 2 int params, in this case automatic type conversion happens and java promotes these 2 int parameters to double and calls overloadedMethod(double i, double j) instead.

Overloaded method in case of Inheritance

In the case of parent-child relationship i.e. inheritance if both classes have the method with same name and same number and type of parameters then it is considered as method overriding, otherwise it is method overloading.

class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overloaded Method with String param
 public void dispayData(String showMsg){
  System.out.println(showMsg + "Value of j " + j);
 } 
}

class OverloadDemo{
 public static void main(String args[]){ 
  Child childObj = new Child(5, 10);
  // This call will invoke the child class method
  childObj.dispayData("in Child class displayData ");
  // This call will invoke the parent class method
  childObj.dispayData();
 }
}

Output of the program would be

in Child class displayData Value of j 10
Value of i 5

Benefit of Method Overloading

If we don't have method overloading then the methods which have same functionality but parameters type or number differs have to have different names, thus reducing readability of the program.

As example- If we have a method to add two numbers but types may differ then there will be different methods for different types like addInt(int a, int b), addLong(long a, long b) and so on with out overloaded methods.

With method overloading we can have the same name for the overloaded methods thus increasing the readability of the program.

That's all for this topic Method Overloading in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Method Overriding in Java
  2. Polymorphism in Java
  3. Inheritance in Java
  4. Difference Between Encapsulation And Abstraction in Java
  5. Java OOP Interview Questions And Answers

You may also like-

  1. Object Creation Using new Operator in Java
  2. final Keyword in Java With Examples
  3. Java Abstract Class and Abstract Method
  4. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  5. How HashMap Works Internally in Java
  6. final Vs finally Vs finalize in Java
  7. Lambda Expressions in Java 8
  8. Dependency Injection in Spring Framework

Monday, May 10, 2021

Object in Java

In object-oriented terms object is an instance of the class, which gets its state and related behavior from the class. An object stores its state in fields and exposes its behavior through methods.

As explained in the post Class in Java when a new class is created essentially a new data type is created. This type can be used to declare objects of that type.

Creating object in Java

Creation of an object for a class in Java is done in three steps-

  • Declaration- Declare a variable of the class type, note that no object is defined yet. This variable can refer to an object as and when the object is created.
  • Instantiation- Create an object and assign it to the variable created in step 1. This object creation is done using new operator.
  • Initialization- Class name followed by parenthesis after the new operator (new classname()) means calling the constructor of the class to initialize the object.

Java object creation example

If we have a class called Rectangle as this-

class Rectangle{
  double length;
  double width;
  
  //methods 
  ……
  ……
}

Then declaring object of the class Rectangle would be done as-

Rectangle rectangle;

This statement declares an object rectangle of the class Rectangle. It does not hold any thing yet.

With the following statement a new object rectangle is created (instantiated), which means rectangle objects holds reference to the created object of Rectangle class.

rectangle = new Rectangle();
Declaring an object in Java
Declaring and Instantiating an object of type Rectangle

As it can be seen from the figure the rectangle variable holds reference to the allocated Rectangle object.

The new operator allocates memory for an object at run time and returns a reference to that memory which is then assigned to the variable of the class type.

In the statement new Rectangle(), the class name Rectangle() followed by parenthesis means that the constructor of the class Rectangle would be called to initialize the newly created object. This step is the initialization step.

Generally this three step process of declaring, creating and initializing an object in Java is written in a single statement as following-

Rectangle rectangle = new Rectangle();

Benefits of using class and object in Java object oriented programming

This encapsulation of variables and methods into a class and using them through objects provides a number of benefits including-

  • Modularity- The application can be divided into different functional categories. Then code can be written for many independent objects implementing the specific functionality. Once created an object can be easily passed around inside the system creating a series of operations to execute functionality.
  • Information-hiding- By encapsulating the variables and methods and providing interaction to the outside entities only through object's methods, an object hides its internal implementation from the outside world.
  • Code re-use- While working on an application we use several third party libraries. That is an example how we use several already existing objects (already created and tested) in our application.
  • Pluggability and debugging ease- Since a whole application comprises of several working components in form of objects, we can simply remove one object and plug in another as replacement in case a particular object is not providing the desired functionality.

That's all for this topic Object in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Object Creation Using new Operator in Java
  2. Object class in Java
  3. this Keyword in Java With Examples
  4. finalize() Method in Java
  5. Java OOP Interview Questions And Answers

You may also like-

  1. Java Abstract Class and Abstract Method
  2. Java Pass by Value or Pass by Reference
  3. Automatic numeric type promotion in Java
  4. final Keyword in Java With Examples
  5. super Keyword in Java With Examples
  6. Deadlock in Java multi-threading
  7. ThreadLocal class in Java
  8. Method Reference in Java

Saturday, May 8, 2021

Class in Java

In object-oriented terms class provides a blue print for the individual objects created from that class. Once a class is defined it can be used to create objects of that type, thus it can be said that class defines new data type.

In this tutorial we'll see how to create a class in Java, how to add a constructor and methods to a class and what all access modifiers can be used with a Java class.

Form of a class in Java

A class has certain properties like data (variables) and the code that uses that data in the code logic. Since class provides a template for an object, thus many individual objects of this class type can be created which will have the basic class properties.

Java class structure

class classname {
  type instance_variable1;
  type instance_variable2;
  …..
  ......

  type methodname1(arguments){
    method code here.....
  }

  type methodname2(arguments){
    method code here.....
  }
}

The variables defined with in a class are called instance variables. The code that operates on these variables is defined with in methods. Together these variables and methods provide the structure of the class.

Java class example

Here is a simple example of defining a class in Java. This step by step example shows how to write a method in a class, how to define a constructor in the class and how to use it to initialize fields, how to create an object of the class.

class Rectangle{
  double length;
  double width;
}

class RectangleDemo {
  public static void main(String[] args) {
    Rectangle rectangle = new Rectangle();
    rectangle.length = 10;
    rectangle.width = 5;
    double area = rectangle.length * rectangle.width;
    System.out.println("Area of the rectangle is " + area);    
  }
}

In this example I have created a class Rectangle which has two instance variables length and width. Then using this template Rectangle (class) new object has been created.

Rectangle rectangle = new Rectangle();

Then values are assigned to the object's instance variables and the area is computed.

We can provide a method in the Rectangle class itself to compute the area, and make the instance variables private to have better encapsulation, the new class will look like this-

class Rectangle{
  private double length;
  private double width;
  // area method to compute area 
  public void area(double ln, double wd){
    length = ln;
    width = wd;
    double area = length * width;
    System.out.println("Area of the rectangle is " + area);
  }
}

class RectangleDemo {
  public static void main(String[] args) {
    Rectangle rectangle = new Rectangle();
    //rectangle.length = 10;
    //rectangle.width = 5;
    //double area = rectangle.length * rectangle.width;
    //System.out.println("Area of the rectangle is " + area); 
    rectangle.area(5, 10);
  }
}

But you must be wondering why this double work of passing the variables and then in the method assigning the values to the instance variables. Yes you can use constructor to do this.

So, we can make the Java class even better by introducing constructor for the class, the initialization of the instance variables will be done through the constructor in that case. With these changes the class will look like this -

class Rectangle{
 double length;
 double width;
 //Constructor
 public Rectangle(double length, double width) {
  this.length = length;
  this.width = width;
 }
 // Method to compute area
 public void area(){
  double area = length * width;
  System.out.println("Area of the rectangle is " + area);
 }
}

 class RectangleDemo { 
 public static void main(String[] args) {
  Rectangle rectangle = new Rectangle(10, 5);  
  rectangle.area();
 }
}

Modifiers for a class in Java

Modifiers for a class may be classified into two categories-

  • Access modifiers
  • Non-Access modifiers

Access modifiers for a Java class

Classes in Java can only have the default (package) and public access modifiers assigned to them.

  • Public- class may be declared with the modifier public, in which case that class is visible to all classes everywhere.
  • Default- If a class in Java has no modifier (the default, also known as package-private), it is visible only within its own package.

Note that an inner class can be declared as private but top level class can take only the above mentioned 2 modifiers.

Non Access modifiers for a Java class

Non access modifiers for the class in Java are-

Points to note-

  • class provides a blue print for the individual objects created from that class.
  • The variables defined with in a class in Java are called instance variables.
  • The code that operates on these variables is enclosed with in methods.
  • Together these variables and methods provide the structure of the class.
  • Access modifiers used with the class are default (package)and public
  • An inner class can be declared as private.
  • Non access modifiers for the class are final, abstract and strictfp

That's all for this topic Class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Object in Java
  2. Package in Java
  3. Java Abstract Class and Abstract Method
  4. TypeWrapper Classes in Java
  5. Java OOP Interview Questions And Answers

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. this Keyword in Java With Examples
  3. How to Read Input From Console in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. equals() And hashCode() Methods in Java
  6. Creating a Thread in Java
  7. Java Exception Handling Tutorial
  8. Java Object Cloning - clone() Method

Monday, March 1, 2021

Association, Aggregation And Composition in Java

When you model a system you can see that most of the classes collaborate with each other in many ways. In object-oriented modelling there are broadly three kind of relationships.

  1. Dependencies
  2. Generalizations
  3. Associations
This post is about association and two types of associations:
  • Aggregation
  • Composition

Many people get confused about these terms so I’ll try to define Association, Aggregation and composition with Java examples, how these terms relate to each other and what are the differences among Association, Aggregation and Composition.

Sunday, February 21, 2021

Difference Between Encapsulation And Abstraction in Java

Encapsulation and Abstraction are two of the fundamental OOP concepts other two being Polymorphism and Inheritance. Some times people do get confused between encapsulation and abstraction as both are used to "hide something". So in this post let's try to see the difference between encapsulation and abstraction in Java.

First let's try to define these two OOPS concepts encapsulation and abstraction to get a better idea-
  • Encapsulation- Encapsulation means keeping together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity. So, in a way Encapsulation is more about data hiding.

    It is a Java class which is the foundation of encapsulation in Java.

    Following image shows the concept of encapsulation. Fields and methods are encapsulated with in the class and the methods of the class can access and manipulate fields. Outside entity can't access fields directly but need to call methods which in turn can access data.

Saturday, January 9, 2021

Inheritance in Java

Inheritance is one of the four fundamental OOP concepts. The other three being- Encapsulation, Polymorphism, Abstraction.


Inheritance Concept

Inheritance is a mechanism, by which one class acquires, all the properties and behaviors of another class. The class whose members are inherited is called the Super class (or base class), and the class that inherits those members is called the Sub class (or derived class).

The relationship between the Super and inherited subclasses is known as IS-A relationship.

As Example- If Shape is a super class and there are subclasses Circle and Rectangle derived from the Shape super class then Circle IS-A Shape and Rectangle IS-A shape.

Polymorphism in Java

Polymorphism is one of the four fundamental OOPS concepts. The other three are Inheritance, Encapsulation, Abstraction. In this post we'll see examples of Polymorphism in Java.


Polymorphism Concept

Polymorphism, a Greek word, where poly means many and morph means change, refers to the ability of an object taking many forms.

The concept of polymorphism is often expressed as "One interface, multiple methods". Where one general class may have the generic method and the derived classes (classes which extend the general class) may add class specific implementation to that method. At the time of execution "One interface" i.e. the general class will take "many forms" i.e. references of the derived classes (See example to have clarity).

Friday, January 8, 2021

Abstraction in Java

Abstraction is one of the four fundamental OOP concepts. The other three being- Inheritance, Polymorphism, Encapsulation

Abstraction Concept

Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, abstraction means abstracting/hiding the real working (implementation details) and we, as a user, knowing only how to use it.

Real world example of abstraction would be-

  • A vehicle which we drive with out caring or knowing what all is going underneath.
  • A TV set where we enjoy programs with out knowing the inner details of how TV works.

An example of abstraction in Java is- Java Database Connectivity (JDBC) API which provides universal data access from the Java programming language. Using the JDBC API, we can access virtually any data source without knowing how the driver for that particular data source is implemented. All we have is an API with a given set of methods.

Encapsulation in Java

Encapsulation is one of the four fundamental OOP concepts. The other three are- Inheritance, Polymorphism, Abstraction


What is Encapsulation

The concept of Encapsulation is to keep together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity.

Encapsulation also helps in maintaining code as the implementation that may change and evolve is kept at one place which makes it easy to change with out impacting other classes in application.