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

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, October 2, 2020

Difference between Inheritance and Polymorphism in Java and Object Oriented Programming

Both Inheritance and Polymorphism are key OOP concepts and similar to Abstraction and Encapsulation, they are also closely related to each other. Because of their similarities, many OOP programmers, especially beginners get confused between Inheritance and Polymorphism. Even though they are closely related and you need Inheritance to support runtime Polymorphism they are a totally different concept. Inheritance refers to the ability for classes or objects to inherit properties of other classes or interfaces. It means you can write code for common functionalities and reuse it at different places by just using Inheritance and not re-writing those codes again and again. For example, you can write code to

Inheritance vs Polymorphism in Java and Object-Oriented Programming

Let's revisit some key differences between Inheritance and Polymorphism in object-oriented programming

1) Class vs Object

Inheritance is used to define a class or interface hierarchy. You extract common functionality on superclass and allow derived classes to get more specific by adding specific functionality. On the other hand, Polymorphism allows you to do the same operation differently depending upon which context and which object is doing the operation.

2)  Code Reuse

One of the key advantages of Inheritance is code reuse. You don't need to write the same code again and again if it is needed by multiple classes. You can extract the common functionality on the base class and let other classes simply use inheritance to get that functionality. In another word, it reduces the amount of duplicate code and promotes DRY practice.

For example, if you are designing a class hierarchy for Finance and Insurance industry, you can create a base class called Insurance, which should have basic properties like covered, the sum assured, premium, etc.

Now, if your application needs to support automobile insurance like the CarInsurance, it just needs to extend the Insurance base class to add specific details required by car insurance companies like the registration number of the car, brand, etc.

Similarly, Health Insurance applications can reuse the same base class for calculating premiums, keeping a record of sum assured, and other basic details. They can further enrich the derived class by adding more specific details required by health insurance companies like pre-existing diseases, co-payment details, etc.

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

Polymorphism can also come handy here to write code for calculating premiums. Assuming, the premium is calculated differently for different types of insurance then you can override the calculatePremium() method in derived or subclasses to represent different types of premium calculation.

The benefit of using Polymorphism here is that all the common functionality like report generations, sending premium receipts, or premium reminders can still use the same the calculatePreimum() method for performing their duty. They don't need to worry about the fact that different types of insurance are calculating premium using different formulas.

3)  Flexibility

If Inheritance provides "code re-usability" then Polymorphism provides the "flexibility" to your code. As I mentioned in my previous example, you can add a new kind of Insurance without re-writing code to generate receipts, premium reminders, and other kinds of reports.
By using Polymorphism, you can encapsulate the code which is different inside the same method declared by the superclass. The Clean Code by Uncle Bob has a good write up and example on this.

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

4)  Right Usage

One of the best practices in the OOP world is using Inheritance for defining type hierarchies using the interface. This is also advised in Effective Java 2nd Edition by Joshua Bloch. By defining types, you create a path for Polymorphism.

5) extends vs implements

Inheritance in Java is implemented using "extends" and "implements" keyword. A class can extend another class or implement one or more interfaces. When it does that, the parent-child relationship is established between two classes or interfaces.

For example, in the following code, the MyClass is now a child or both Canvas and Runnable:

public class MyClass extends Canvas implements Runnable{

@Overide
public void paint(Graphics g){
   ... some code
  }

@Override
public void run(){
  ... some code
  }

}

This means you a reference variable of Runnable or Canvas can point to an object of MyClass and if you call paint() or run() method then these methods will be called instead of paint() method defined in Canvas and run() method defined in Runnable. This is the power of Polymorphism which comes from Inheritance.

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

Source: javarevisited.blogspot.com

Friday, July 3, 2020

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.

Terms used in Inheritance

◉ Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.

◉ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.

◉ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.

◉ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name 

   //methods and fields 


The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Java Inheritance Example


Java Inheritance, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  

Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Java Inheritance, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Java Inheritance, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class TestInheritance{  
public static void main(String args[]){  
Dog d=new Dog();  
d.bark();  
d.eat();  
}}  

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}  

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("meowing...");}  
}  
class TestInheritance3{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}  

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
   
 public static void main(String args[]){  
   C obj=new C();  
   obj.msg();//Now which msg() method would be invoked?  
}  
}  

Compile Time Error