Friday, August 11, 2023
Quiz yourself: Abstract classes and the difference between Java’s super() and this()
Friday, October 14, 2022
Implement Interface using Abstract Class in Java
1. Let’s create an Interface at first:
2. Now let’s implement the interface in an Abstract class named Student:
3. Now let’s create a class JAVA which extends the abstract class, Student:
Output:
Wednesday, January 19, 2022
Quiz yourself: Java abstract classes and access modifiers for abstract methods
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 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:
Implementation:
Friday, July 16, 2021
Difference Between Abstract Class and Concrete Class
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
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?
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 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(); } |
Example of abstract class and interface in Java
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.
When to use what?
- 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).
- 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 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. |
2 | 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. |
3 | final variables | An abstract class may or may not have variables declared as final | In interfaces, variables are by default declared as final. |
4 | 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. |
5 | 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. |
6 | Constructors | An abstract class can have constructors | An interface can not have constructors |
7 | 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. |
8 | Implementation | We can extend an abstract class using the extends keyword. | We can implement an interface using the implements keyword. |
9 | 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 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?
◉ When you want to specify the behavior of a particular data type irrespective of who implements its behavior.