Showing posts with label Java Abstract Class. Show all posts
Showing posts with label Java Abstract Class. Show all posts

Friday, August 11, 2023

Quiz yourself: Abstract classes and the difference between Java’s super() and this()

Quiz Yourself, Abstract classes, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation


Given the following two classes

01:  abstract class SupA {
02:    SupA() { this(null); }
03:    SupA(SubA s) {this.init();}
04:    abstract void init();
05:  }
06:  class SubA extends SupA {
07:    void init() {System.out.print("SubA");}
08:  }

Which statement is correct if you try to compile the code and create an instance of SubA? Choose one.

A. Compilation fails at line 02.
B. Compilation fails at line 03.
C. A runtime exception occurs at line 02.
D. A runtime exception occurs at line 03.
E. SubA is printed.
F. SubASubA is printed.

Answer. This question investigates object initialization, overridden method invocation, and the difference between this() and this.

Consider the process of instantiating and initializing an object, and assume that the class and all its parent types are fully loaded and initialized at the point of instantiation.

◉ First, the invocation of new causes the allocation of memory for the entire object, including all the parent elements of which it is made. That memory is also zeroed in this phase.
◉ Next, assuming no errors (such as running out of memory) occur in the first step, control is transferred to the constructor with an argument type sequence that matches, or is compatible with, the actual parameters of the invocation.

In contemporary releases of Java, including Java 17 and later, all constructors start with one of three code elements. First, there is an implicit call to super() with no arguments. This is followed by either an explicit call to super(...), which may take arguments, or by a call to this(...), which, again, may take arguments. Strictly, evaluation of any actual parameters to these calls executes before those delegating calls. (Note that there’s a proposal to allow explicit code to be placed before those calls, provided no reference is made to the uninitialized this object, but that’s for the future.)

The class SupA has two constructors. The one on line 02 delegates to the one on line 03 using this(null), while the one on line 03 has an implicit call to super().

The class SubA has no explicit constructors; therefore, the compiler gives it an implicit constructor, which delegates using super().

From that outline, consider the flow of construction and initialization of an instance of SubA.

First, the invocation new SubA() begins by allocating and zeroing memory for the entire object, including the storage necessary for the SubA, SupA, and Object parts. There are no instance fields in the code you see in this question, but the principle is the same.

Next, the newly allocated object is passed as the implicit this argument into the implicit constructor for SubA. That constructor immediately delegates—using super()—to the zero-argument constructor for SupA. That constructor in turn immediately delegates to the one-argument constructor for SupA on line 03 using the explicit call this(null).

The body of the constructor on line 03 begins with an implicit call to super() that was generated by the compiler. That call passes control up to the zero-argument constructor of java.lang.Object. When control returns from the constructor, any instance initialization on the SupA class would be executed, but of course there is none in this case. So, execution continues with the explicit body of the constructor. The constructor body calls this.init();, which invokes the implementation on line 07 and prints the message SubA. At that point, the constructor on line 03 is finished and control returns to the constructor on line 02, which also is finished since there’s no more code after this(null).

After all the constructors for SupA have finished, control returns to the implicit constructor of SubA. The implicit constructor would then perform any instance initialization called for by the SubA class, but there is none. At this point, the construction and initialization process has been completed.

Notice that in the description above, the message SubA was printed exactly once, which makes option E the correct answer and options A, B, C, D, and F incorrect.

To dive deeper, here are some specific considerations for clarification and additional points.


A call of the form this() (with parentheses) is a call to an overloaded constructor in the same class. Contrast this with the reference this, which is an explicit reference to the current instance of the class. The second form (this without parentheses) is the prefix used explicitly to invoke the init() method. Also note that init() is an ordinary instance method that implements the abstract method declared in SupA; Java does not attach any special meaning to the name init.

The constructor on line 02 passes null to the constructor on line 03. There’s nothing tricky here. If the constructor on line 03 attempted to refer to the object, it would cause a null pointer exception, but because no such reference is made, there is no problem.

The call to this.init() on line 03 is entirely valid and safe. It’s not possible to enter a constructor except via a call to new, and new must be followed by a concrete class name. This in turn means that the object referred to by this on line 03 must have a proper implementation of the init() method.

Creating a new instance of SubA does not cause an instance of SupA to be created, so there is only one instance, and when you call this.<something>, it will be tried on SubA. If this element is missing, it will be looked up for an inherited element in superclasses. In the case of the init() method, it will be directly present in SubA, so it will be called when the this.init(); statement runs.

One more point regarding good coding practice: Although it’s done in this question, it’s a bad idea to call overridable methods during instance initialization, for two reasons.

◉ The code that’s executed might not be what the programmer intended when the parent class was written.
◉ If the invocation occurs during initialization of a parent class but invokes an implementation in a subclass, the subclass implementation might refer to fields in the subclass that have not yet been initialized. This can cause unexpected behavior and commonly causes null pointer exceptions.

Conclusion. The correct answer is option E.

Source: oracle.com

Friday, October 14, 2022

Implement Interface using Abstract Class in Java

Java Interface, Abstract Class, Java Career, Java Prep, Java Preparation, Java Tutorial and Materials, Java Certification, Java Jobs

Interface contains only abstract methods that can’t be instantiated and it is declared by keyword interface. A class that is declared with the abstract keyword is known as an abstract class in Java. This is a class that usually contains at least one abstract method which can’t be instantiated and It is also possible for the class to have no methods at all. The instance of an abstract class can’t be created.

Now as all methods in an interface are abstract methods therefore we can implement it using Abstract Class.

1. Let’s create an Interface at first:


// creating an interface named ORACLEJAVACERTIFIED 
interface ORACLEJAVACERTIFIED { 
void learnCoding(); 
void learnProgrammingLanguage(); 
void contribute(); 
}

Here the three  non-implemented methods are the abstract methods

2. Now let’s implement the interface in an Abstract class named Student:


// creating an abstract class named Student which is 
// implementing the interface,ORACLEJAVACERTIFIED 
abstract class Student implements ORACLEJAVACERTIFIED { 
// Overriding two methods of the interfacem,ORACLEJAVACERTIFIED
@Override public void learnCoding() 
System.out.println( 
"Let's make coding a habit with ORACLEJAVACERTIFIED"); 
@Override public void learnProgrammingLanguage() 
System.out.println( 
"Let's master all fundamentals of java with the help of ORACLEJAVACERTIFIED"); 
}

Here we have overridden two abstract methods of the interface ORACLEJAVACERTIFIED.

3. Now let’s create a class JAVA which extends the abstract class, Student:


As previously mentioned, we can’t create an instance of our abstract class therefore we need to make a non-abstract class.

// creating an non-abstract class 
// JAVA which is extending Student 
class JAVA extends Student { 
// overriding the remaining method of the interface,ORACLEJAVACERTIFIED 
@Override public void contribute() 
System.out.println( 
"Now let's help others by contributing in ORACLEJAVACERTIFIED"); 
}

Here we have overridden the remaining method of the interface ORACLEJAVACERTIFIED.

Below is the overall implementation of the problem statement:

// Implemention of Interface using Abstract Class in Java 

// Interface ORACLEJAVACERTIFIED 
interface ORACLEJAVACERTIFIED { 
void learnCoding(); 
void learnProgrammingLanguage(); 
void contribute(); 

// Abstract class Student implementing from ORACLEJAVACERTIFIED interface 
abstract class Student implements ORACLEJAVACERTIFIED { 

// Overriding the methods 
@Override public void learnCoding() 
System.out.println( 
"Let's make coding a habit with ORACLEJAVACERTIFIED"); 
@Override public void learnProgrammingLanguage() 
System.out.println( 
"Let's master all fundamentals of java with the help of ORACLEJAVACERTIFIED"); 

// Extend the JAVA class by Student abstract class 
class JAVA extends Student { 
@Override public void contribute() 
System.out.println( 
"Now let's help others by contributing in ORACLEJAVACERTIFIED"); 

// Driver code 
public class Main { 
public static void main(String[] args) 
// New JAVA object is created 
JAVA oraclejavacertifiedStudent = new JAVA(); 

// Calls to the multiple functions 
oraclejavacertifiedStudent.learnCoding(); 
oraclejavacertifiedStudent.learnProgrammingLanguage(); 
oraclejavacertifiedStudent.contribute(); 
}

Output:


Let's make coding a habit with ORACLEJAVACERTIFIED
Let's master all fundamentals of java with the help of ORACLEJAVACERTIFIED
Now let's help others by contributing in ORACLEJAVACERTIFIED

Source: geeksforgeeks.org

Wednesday, January 19, 2022

Quiz yourself: Java abstract classes and access modifiers for abstract methods

Core Java, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Preparation, Oracle Java Career, Oracle Java Guides

It’s essential to declare classes properly to ensure methods are accessible.

Download a PDF of this article

Your software uses two classes that are part of the Object Relational Mapping (ORM) framework.

package orm.core;

public abstract class Connection {

  abstract void connect(String url);  

}

package orm.impl;

import orm.core.Connection;

public abstract class DBConnection extends Connection {

  protected void connect(String url) { /* open connection */ }

}

You have decided to create your own concrete connection class based on the DBConnection class.

package server;

import orm.impl.DBConnection;

public class ServerDBConnection extends DBConnection {

  ...

}

Which statement is correct? Choose one.

A. The Connection class fails to compile.

B. The DBConnection class fails to compile.

C. The ServerDBConnection class cannot be properly implemented.

D. The ServerDBConnection class successfully compiles if you provide the following method inside the class body:

public void connect(String url) { /* */ }

Answer. This question investigates abstract classes and access modifiers for abstract methods.

Option A is incorrect because the Connection class is properly declared: It declares an abstract method, but that’s permitted since it is an abstract class. However, notice that the connect() method has a default accessibility, which means that it’s accessible only inside the orm.core package. This has consequences for how it can be implemented.

As a side note, an abstract method cannot have private accessibility. A private element of a parent class is essentially invisible from the source of a child type. Consequently a private abstract method could never be implemented, so that combination is prohibited.

Consider option B. The DBConnection class successfully compiles. Although it neither sees nor implements the Connection.connect() method, that does not cause a problem. Why? Because the DBConnection class is marked as abstract, it’s acceptable for it to contain abstract methods, whether from a superclass or declared in its own body. Because the class compiles, option B is incorrect.

Option D is also incorrect: Attempting to add a public connect() method in the ServerDBConnection class cannot provide an implementation for the abstract method in the Connection class because it’s not in the orm.core package.

Unless the ServerDBConnection class is in the package orm.core, the ServerDBConnection class cannot implement the Connection.connect() method. Knowing this fact is at the heart of this question.

Because the code cannot implement all the abstract methods from the ServerDBConnection class’s parentage, it cannot be properly defined as a concrete class. This makes option C correct.

To fix the code, you can add the protected access modifier before the Connection.connect() method. The modifier will make DBConnection.connect() implement the method properly, and the ServerDBConnection class could even compile without providing an implementation of the connect() method.

Alternatively, moving the ServerDBConnection class into the orm.core package would allow a proper implementation of the connect() method in its current form.

Conclusion. The correct answer is option C.

Source: oracle.com

Monday, August 16, 2021

Abstract Syntax Tree (AST) in Java

Abstract Syntax Tree (AST) in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career

Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.

There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to represent the structure of program code. An AST is usually the result of the syntax analysis phase of a compiler. It often serves as an intermediate representation of the program through several stages that the compiler requires, and has a strong impact on the final output of the compiler.

Let us do discuss the use of AST before proceeding further to the implementation part. AST’s are mainly used in compilers to check code for their accuracy. If the generated tree has errors, the compiler prints an error message. Abstract Syntax Tree (AST) is used because some constructs cannot be represented in context-free grammar, such as implicit typing. They are highly specific to programming languages, but research is underway on universal syntax trees.

Flow Chart:  

id + id * id would have the following syntax tree which is as follows:

Abstract Syntax Tree (AST) in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career

Abstract syntax tree will be as follows:

Abstract Syntax Tree (AST) in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career

Implementation:


Here we will be writing custom java source codes corresponding to which we will be providing the AST for the same java source code as in implementation.

Example 1(A) Java source code

Java

// Java Custom Source Code

// Main class
class GFG {

// Main driver method
public static void main(String[] args)
{

// Print statement
System.out.println("Hello World!");
}
}

Example 1(B) AST of above source code

Java

CLASS_DEF -> CLASS_DEF [1:0]
|--MODIFIERS -> MODIFIERS [1:0]
| `--LITERAL_PUBLIC -> public [1:0]
|--LITERAL_CLASS -> class [1:7]
|--IDENT -> GFG [1:13]
`--OBJBLOCK -> OBJBLOCK [1:17]
|--LCURLY -> { [1:17]
|--METHOD_DEF -> METHOD_DEF [2:4]
| |--MODIFIERS -> MODIFIERS [2:4]
| | |--LITERAL_PUBLIC -> public [2:4]
| | `--LITERAL_STATIC -> static [2:11]
| |--TYPE -> TYPE [2:18]
| | `--LITERAL_VOID -> void [2:18]
| |--IDENT -> main [2:23]
| |--LPAREN -> ( [2:27]
| |--PARAMETERS -> PARAMETERS [2:34]
| | `--PARAMETER_DEF -> PARAMETER_DEF [2:34]
| | |--MODIFIERS -> MODIFIERS [2:34]
| | |--TYPE -> TYPE [2:34]
| | | `--ARRAY_DECLARATOR -> [ [2:34]
| | | |--IDENT -> String [2:28]
| | | `--RBRACK -> ] [2:35]
| | `--IDENT -> args [2:37]
| |--RPAREN -> ) [2:41]
| `--SLIST -> { [2:43]
| |--EXPR -> EXPR [3:26]
| | `--METHOD_CALL -> ( [3:26]
| | |--DOT -> . [3:18]
| | | |--DOT -> . [3:14]
| | | | |--IDENT -> System [3:8]
| | | | `--IDENT -> out [3:15]
| | | `--IDENT -> println [3:19]
| | |--ELIST -> ELIST [3:27]
| | | `--EXPR -> EXPR [3:27]
| | | `--STRING_LITERAL -> "Hello World!" [3:27]
| | `--RPAREN -> ) [3:41]
| |--SEMI -> ; [3:42]
| `--RCURLY -> } [4:4]
`--RCURLY -> } [5:0]

Now you must be wondering how to make an AST or how the above code is generated for that geek follow the simple steps as listed in the sequential order. 

◉ Run the Source Code in your local Environment.

checkstyle-8.43-all.jar 

◉ Audit the Program with the help of Checkstyle in your Terminal:

java -jar checkstyle-8.43-all.jar -c /google_checks.xml YourFile.java

◉ After Audit, Run this command in your terminal to get the AST of your preferred  Code: java -jar checkstyle-8.43-all.jar -t YourFile.java

◉ AST is now ready. But wait geeks,

Note: This is not an Updated AST

Remember: To update the AST, we have to do the following two steps

Step 1: We should replace 

">" with "&gt;" and "<" with "&lt;"

Step 2: Remove the code lines

Example 1(C) Updated AST Examples of the above code is as follows:

Java

CLASS_DEF -> CLASS_DEF
|--MODIFIERS -> MODIFIERS
| `--LITERAL_PUBLIC -> public
|--LITERAL_CLASS -> class
|--IDENT -> GFG
`--OBJBLOCK -> OBJBLOCK
|--LCURLY -> {
|--METHOD_DEF -> METHOD_DEF
| |--MODIFIERS -> MODIFIERS
| | |--LITERAL_PUBLIC -> public
| | `--LITERAL_STATIC -> static
| |--TYPE -> TYPE
| | `--LITERAL_VOID -> void
| |--IDENT -> main
| |--LPAREN -> (
| |--PARAMETERS -> PARAMETERS
| | `--PARAMETER_DEF -> PARAMETER_DEF
| | |--MODIFIERS -> MODIFIERS
| | |--TYPE -> TYPE
| | | `--ARRAY_DECLARATOR -> [
| | | |--IDENT -> String
| | | `--RBRACK -> ]
| | `--IDENT -> args
| |--RPAREN -> )
| `--SLIST -> {
| |--EXPR -> EXPR
| | `--METHOD_CALL -> (
| | |--DOT -> .
| | | |--DOT -> .
| | | | |--IDENT -> System
| | | | `--IDENT -> out
| | | `--IDENT -> println
| | |--ELIST -> ELIST
| | | `--EXPR -> EXPR
| | | `--STRING_LITERAL -> "Hello World!"
| | `--RPAREN -> )
| |--SEMI -> ;
| `--RCURLY -> }
`--RCURLY -> }

Example 2: Representing 1 + 2 can be represented in AST 

Java

+ BinaryExpression
- type: +
- left_value:
LiteralExpr:
value: 1
- right_vaue:
LiteralExpr:
value: 2

Source: geeksforgeeks.org

Friday, July 16, 2021

Difference Between Abstract Class and Concrete Class

Oracle Java Abstract Class, Oracle Java Concrete Class, Oracle Java Exam Prep, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Material, Oracle Java Guides

Abstract Class vs Concrete Class

Most of the popular modern object oriented programming languages like Java and C# are class based. They achieve the object oriented concepts such as encapsulation, inheritance and polymorphism through the use of classes. Classes are an abstract representation of real world objects. Classes can be either concrete or abstract depending on the level of implementation of their method functionalities. A concrete class completely implements all its methods. An abstract class can be considered as a limited version of a regular (concrete) class, where it may contain partially implemented methods. Typically, concrete classes are referred to as (just) classes.

What is Concrete Class?

The default class is a concrete class. The class keyword is used to define classes (e.g. in Java). And usually they are simply referred to as classes (without the adjective concrete). Concrete classes depict the conceptual representation of real world objects. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. An object is the instance of a class. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Public, private and protected are the typical access modifiers used for classes.

What is Abstract Class?

Abstract classes are declared using Abstract keyword (e.g. in Java,). Typically, Abstract classes, also known as Abstract Base Classes (ABC), cannot be instantiated (an instance of that class cannot be created). So, Abstract classes are only meaningful to have if the programming language supports inheritance (ability to create subclasses from extending a class). Abstract classes usually represent an abstract concept or entity with partial or no implementation. Therefore, Abstract classes act as parent classes from which child classes are derived so that the child class will share the incomplete features of the parent class and functionality can be added to complete them.

Abstract classes may contain Abstract methods. Subclasses extending an abstract class may implement these (inherited) Abstract methods. If the child class implements all such Abstract methods, it becomes a concrete class. But if it does not, the child class also becomes an Abstract class. What all this means is that, when the programmer nominates a class as an Abstract, she is saying that the class will be incomplete and it will have elements that need to be completed by the inheriting subclasses. This is a nice way to create a contract between two programmers, which simplifies tasks in software development. The programmer, who writes code to inherit, needs to follow the method definitions exactly (but of course can have her own implementation).

What is the difference between Abstract Class and Concrete Class?

Abstract classes usually have partial or no implementation. On the other hand, concrete classes always have full implementation of its behavior. Unlike concrete classes, abstract classes cannot be instantiated. Therefore abstract classes have to be extended in order to make them useful. Abstract classes may contain abstract methods, but concrete classes can’t. When an abstract class is extended, all methods (both abstract and concrete) are inherited. The inherited class can implement any or all the methods. If all the abstract methods are not implemented, then that class also becomes an abstract class.

Source: differencebetween.com

Monday, April 5, 2021

Difference Between Abstract Class and Inheritance

Oracle Java Abstract Class, Oracle Java Inheritance, Oracle Java Career, Oracle Java Prep, Java Preparation

Abstract Class vs Inheritance

Abstract class and Inheritance are two important object oriented concepts found in many object oriented programming languages like Java. Abstract class can be considered as an abstract version of a regular (concrete) class, while Inheritance allows new classes to extend other classes. Abstract class is a class that cannot be initialized but can be extended. So, Abstract classes are only meaningful to have if the programming language supports inheritance. In Java, Abstract classes are declared using Abstract keyword, while Extends keyword is used for inheriting from a (super) class.

What is  Abstract Class?

Typically, Abstract classes, also known as Abstract Base Classes (ABC), cannot be instantiated (an instance of that class cannot be created). So, Abstract classes are only meaningful to have if the programming language supports inheritance (ability to create subclasses from extending a class). Abstract classes usually represent an abstract concept or entity with partial or no implementation. Therefore, Abstract classes act as parent classes from which child classes are derived so that the child class will share the incomplete features of the parent class and functionality can be added to complete them.

Abstract classes may contain Abstract methods. Subclasses extending an abstract class may implement these (inherited) Abstract methods. If the child class implements all such Abstract methods, it is a concrete class. But if it does not, the child class also becomes an Abstract class. What all this means is that, when the programmer nominates a class as an Abstract, she is saying that the class will be incomplete and it will have elements that need to be completed by the inheriting subclasses. This is a nice way to create a contract between two programmers, which simplifies tasks in software development. The programmer, who writes code to inherit, needs to follow the method definitions exactly (but of course can have her own implementation).

What is Inheritance?

Oracle Java Abstract Class, Oracle Java Inheritance, Oracle Java Career, Oracle Java Prep, Java Preparation

Inheritance is an object oriented concept, which allows new classes to extend other classes. Extends keyword is used to implement the concept of inheritance in Java programming language. Inheritance essentially provides code reuse by allowing extending properties and behavior of an existing class by a newly defined class. When a new subclass (or derived class) extends a super class (or parent class) that subclass will inherit all attributes and methods of the super class. The subclass can optionally override the behavior (provide new or extended functionality to methods) inherited from the parent class. Typically, A subclass cannot extend multiple super classes (e.g. in Java). Therefore, you cannot use extends for multiple inheritance. In order to have multiple inheritance, you need to use interfaces.

What is the difference between Abstract Class and Inheritance?

Abstract classes usually represent an abstract concept or an entity with partial or no implementation. Inheritance allows new classes to extend other classes. Because, Abstract classes cannot be instantiated, you need to use the concept of inheritance to make use of Abstract classes. Otherwise, an Abstract class has no use. Abstract classes may contain Abstract methods and when the class is extended, all methods (Abstract and concrete) are inherited. The inherited class can implement any or all the methods. If all the Abstract methods are not implemented, then that class also becomes an Abstract class. A class cannot inherit from more than one Abstract class (this is not a quality of Abstract classes per se, but rather a restriction of inheritance).

Friday, February 19, 2021

Difference between abstract class and interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Guides

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface 
Abstract class can have abstract and non-abstract methods.  Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
Abstract class doesn't support multiple inheritance.  Interface supports multiple inheritance. 
Abstract class can have final, non-final, static and non-static variables.  Interface has only static and final variables. 
Abstract class can provide the implementation of interface.  Interface can't provide the implementation of abstract class. 
The abstract keyword is used to declare abstract class.  Interface can't provide the implementation of abstract class. 
An abstract class can extend another Java class and implement multiple Java interfaces.  An interface can extend another Java interface only. 
An abstract class can be extended using keyword "extends".  An interface can be implemented using keyword "implements". 
A Java abstract class can have class members like private, protected, etc.  Members of a Java interface are public by default. 
Example:
public abstract class Shape{
public abstract void draw();
Example:
public interface Drawable{
void draw();

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods  
interface A{  
void a();//bydefault, public and abstract  
void b();  
void c();  
void d();  
}  
  
//Creating abstract class that provides the implementation of one method of A interface  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
  
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
//Creating a test class that calls the methods of A interface  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  

Output:

I am a
I am b
I am c
I am d

Monday, October 5, 2020

Difference between Abstract Class and Interface in Java

Prerequisite

Interface

An interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).

Abstract Class

Abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

Abstraction: Hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction.

Abstract class vs Interface

1. Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.

2. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.

3. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.

4. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.

5. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”.

6. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.

7. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep

// Java program to illustrate the 
// concept of abstract class 

import java.io.*; 

// abstract class 
abstract class Shape 
// declare fields 
String objectName = " "; 
Shape(String name) 
this.objectName = name; 
// declare non-abstract methods 
// it has default implementation 
public void moveTo(int x, int y) 
System.out.println(this.objectName + " " + "has been moved to"
+ " x = " + x + " and y = " + y); 
// abstract methods which will be 
// implemented by its subclass(es) 
abstract public double area(); 
abstract public void draw(); 

class Rectangle extends Shape 
int length, width; 
// constructor 
Rectangle(int length, int width, String name) 
super(name); 
this.length = length; 
this.width = width; 
@Override
public void draw() 
System.out.println("Rectangle has been drawn "); 
@Override
public double area() 
return (double)(length*width); 

class Circle extends Shape 
double pi = 3.14; 
int radius; 
//constructor 
Circle(int radius, String name) 
super(name); 
this.radius = radius; 
@Override
public void draw() 
System.out.println("Circle has been drawn "); 
@Override
public double area() 
return (double)((pi*radius*radius)/2); 

class GFG 
public static void main (String[] args) 
// creating the Object of Rectangle class 
// and using shape class reference. 
Shape rect = new Rectangle(2,3, "Rectangle"); 
System.out.println("Area of rectangle: " + rect.area()); 
rect.moveTo(1,2); 
System.out.println(" "); 
// creating the Objects of circle class 
Shape circle = new Circle(2, "Cicle"); 
System.out.println("Area of circle: " + circle.area()); 
circle.moveTo(2,4); 

Output:

Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2
 
Area of circle: 6.28
Cicle has been moved to x = 2 and y = 4

In you don’t have any common code between rectangle and circle then go with interface.

// Java program to illustrate the 
// concept of interface 
import java.io.*; 

interface Shape 
// abstract method 
void draw(); 
double area(); 

class Rectangle implements Shape 
int length, width; 
// constructor 
Rectangle(int length, int width) 
this.length = length; 
this.width = width; 
@Override
public void draw() 
System.out.println("Rectangle has been drawn "); 
@Override
public double area() 
return (double)(length*width); 

class Circle implements Shape 
double pi = 3.14; 
int radius; 
//constructor 
Circle(int radius) 
this.radius = radius; 
@Override
public void draw() 
System.out.println("Circle has been drawn "); 
@Override
public double area() 
return (double)((pi*radius*radius)/2); 

class GFG 
public static void main (String[] args) 
// creating the Object of Rectangle class 
// and using shape interface reference. 
Shape rect = new Rectangle(2,3); 
System.out.println("Area of rectangle: " + rect.area()); 

// creating the Objects of circle class 
Shape circle = new Circle(2); 
System.out.println("Area of circle: " + circle.area()); 

output

Area of rectangle: 6.0
Area of circle: 6.28

When to use what?


Consider using abstract classes if any of these statements apply to your situation:

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep

  • In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
  • You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
  • You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

Consider using interfaces if any of these statements apply to your situation:

  • It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
  • A class can implement more than one interface. It is called multiple inheritance.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

Friday, March 20, 2020

Abstract Class vs Interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Exam Prep

In Java, the Abstract classes and interfaces are fundamental building blocks as they both are used to implement one of the essential concepts of Object-Oriented Programming that is, Abstraction. Though both of them are used for Abstraction, they differ from each other, and we cannot use them interchangeably. We will compare abstract class vs interface, along with real-life examples. We will also discuss when we should use interfaces and abstract classes.

Abstract Class In Java


An Abstract class is a class whose objects can’t be created. It is a kind of guideline or a template for other classes. An abstract class should contain at least one abstract method (method without any implementation or method body).

◉ The abstract class is declared with the help of an abstract keyword.

◉ An abstract class can be considered as an incomplete class that does not represent complete behavior.

◉ The abstract class can have abstract methods (methods without body) as well as concrete methods (methods with the body).

◉ We can not create objects or instances from the abstract classes, but they can be subclassed.

Syntax of writing Abstract classes:

abstract class TestAbstractClass
{
  public abstract void abstractMethod();
  public void normalMethod()
  {
    //method body
  }
}

Reasons For Using Abstract Class in Java


◉ An abstract class provides a guideline or template for other future specific classes.
◉ An Abstract class gives a default functionality of Inheritance.
◉ The abstract class helps in achieving code reusability.
◉ The abstract class also allows us to define a common interface for its subclasses.

Abstract Methods in Java


◉ Abstract methods are methods with no implementation. They do not contain any method statement.

◉ The child classes of this abstract class must provide the implementation of these inherited abstract methods.

◉ An abstract method is declared with an abstract keyword.

◉ The declaration of an abstract method must end with a semicolon ;

Syntax of declaring abstract methods:

access-specifier abstract return-type method-name();

Example of Abstract class:

package com.oraclejavacertified.abstractclass;
//parent class
abstract class Animal
{
  //concrete method
  public void show1()
  {
    System.out.println("Concrete method of parent class Class");
  }
  //abstract method
  abstract public void show2();
  }
//child class
Class Dog extends Animal
{
  // Must Override this method while extending the parent class
  public void show2()
  {
    System.out.println("Overriding abstract method of parent class");
  }
  //Overriding concrete method is not compulsory
  public void show1()
  {
    System.out.println("Overriding concrete method of parent class");
  }
}
public class AbstractClassDemo
{
  public static void main(String[] args)
  {
    Dog obj = new Animal();
    obj.show2();
    obj.show1();
  }
}

Output:

Overriding abstract method of parent class
Overriding concrete method of parent class

Rules to be followed for Abstract Class


◉ The abstract class cannot be instantiated or we can’t create objects from abstract classes.

◉ The child class which extends the abstract class should implement all the abstract methods of the parent class otherwise, the child class should also be declared as an abstract class.


Interfaces in Java


An interface is another building block of Java which is a blueprint or template of a class. It is much similar to the Java class but the only difference is that it has abstract methods and static constants. There can be only abstract methods in an interface, that is there is no method body inside these abstract methods. The class that implements the interface should be declared as abstract, otherwise, all the methods of the interface need to be defined in the class.

Syntax of declaring Interfaces in Java:

To declare an interface, the interface keyword is used. Here is a syntax to declare an interface:

interface interface-name
{
  //abstract methods
}

Example:

Following is an example of an interface:

//Filename: NameOfInterface.java
                    import java.lang.*;
                    // Any number of import statements
                    interface NameOfInterface
                    {
                           // Any number of final, static fields
                           // Any number of abstract method declarations
                    }
Example:

//Filename : Animal.java

interface Animal
{
   public void eat();
   public void travel();
}


Reasons For Using Interfaces in Java


◉ It allows us to achieve a complete abstraction.

◉ Interfaces are mainly designed to support dynamic method resolution at run time.

◉ Interfaces allow us to achieve loose coupling.

◉ It also helps us to separate the definition of a method from the inheritance hierarchy.

Implementing Interfaces


A class implementing an interface can be thought of as the class assigning a contract. This means that the class agrees to perform the specific behaviors of the Interface. Unless a class is declared as abstract, it should perform all the behaviors of the Interface.

In order to implement an Interface in Java, a class uses the implements keyword. The implements keyword appears in the class declaration after the extends portion of the declaration.

Code to understand Interfaces in Java:

package com.oraclejavacertified.interfaces;
interface Polygon
{
  //declaring variables of the interface
  public static final int length = 4,breadth = 8;
  //declaring interface methods(without a method body)
  public void getName();
  public void getNumberOfSides();
  public void getArea();
  public void getPerimeter();
}
// Rectangle class "implements" the Polygon interface
class Rectangle implements Polygon
{
  public void getName()
  {
    // The body of getName() is provided here
    System.out.println("The name of the Polygon is: Rectangle");
  }
  public void getNumberOfSides()
  {
    // The body of getNumberOfSides() is provided here
    System.out.println("There are 4 sides in a Rectangle");
  }
  public void getArea()
  {
    // The body of getArea() is provided here
    System.out.println("The Area of Rectangle is: " +length*breadth);
  }
  public void getPerimeter()
  {
    // The body of getPerimeter() is provided here
    System.out.println("The Perimeter of Rectangle is: " +2*(length + breadth));
  }
}
class InterfaceDemo
{
  public static void main(String[] args)
  {
    Rectangle rectangle = new Rectangle(); // Create a Rectangle object
    //calling methods of class Rectangle
    rectangle.getName();
    rectangle.getNumberOfSides();
    rectangle.getArea();
    rectangle.getPerimeter();
  }
}

Output:

The name of the Polygon is: Rectangle
There are 4 sides in a Rectangle
The Area of Rectangle is: 32
The Perimeter of Rectangle is: 24

Rules to be followed for Interface


◉ The class that implements the Interface should implement all the methods defined in the Interface.

◉ An Interface can also contain final variables.

Abstract Class vs Interface in Java


We will compare Abstract Class vs Interface on the basis of following parameters:

S.No Parameter  Abstract Class   Interfaces 
1 Keyword Used An abstract keyword is used to create an abstract class. An interface keyword is used to create an interface.
Type of variables  Abstract class in Java can have both final, non-final, static and non-static variables.  An interface can only have final and static variables that are declared by default.
final variables  An abstract class may or may not have variables declared as final   In interfaces, variables are by default declared as final. 
Access Modifiers  Abstract classes can have all access modifiers: public, protected, private and default.  No other access modifiers are allowed except the public access modifier. 
Type of Methods  An abstract class can have both abstract and non-abstract or concrete methods.  An interface can only have abstract methods. From version 8 of Java, the interface supports static and non-static methods too. 
Constructors  An abstract class can have constructors  An interface can not have constructors 
Multiple Inheritance  Abstract classes do not support Multiple Inheritance. A class can extend only a single abstract class but can implement multiple Java interfaces.  Interfaces support Multiple Inheritance. 
Implementation  We can extend an abstract class using the extends keyword.  We can implement an interface using the implements keyword. 
Speed  Fast  Slow as it requires extra indirection. 
10  When to use  To avoid independence  For Future enhancement 

When to use Abstract Class?


Consider using abstract classes in the following cases:

◉ If you have some related classes that need to share the same lines of code, then we put these classes in abstract classes.

◉ If there is a requirement of using access modifiers other than public such as protected and private for methods or fields.

◉ When there is a need for defining a state of an object because we need to define a non-static or non-final field.

When to use Interface?


Consider using an interface in the following cases:

◉ When you want to achieve 100% abstraction.

◉ If you want to achieve multiple inheritance, that is, implementing more than one interface.

◉ When you want to specify the behavior of a particular data type irrespective of who implements its behavior.