Showing posts with label method overriding. Show all posts
Showing posts with label method overriding. Show all posts

Thursday, 13 May 2021

Php: Override method definitions in subclass

You can override the properties, methods defined in super class by redefining them in subclasses.

 

overriding_demo.php

#!/usr/bin/php

<?php

   class Employee{
        var $id;
        var $first_name;
        var $last_name;
        var $country='India';
        var $designation = 'Developer';

        function about_me(){
            echo "Hello ($this->first_name,$this->last_name), you are from $this->country\n";
        }
   }

   class Manager extends Employee{
       var $reportee_ids;
       var $designation = 'Engineering Manager';

       function about_me(){
           echo "first_name : $this->first_name\n";
           echo "last_name : $this->last_name\n";
           echo "designation : $this->designation\n";
           echo "Reportee ids : ";
           print_r($this->reportee_ids);
       }
   }

   $manager1 = new Manager();
   $manager1->id = 1;
   $manager1->first_name = 'Vadiraj';
   $manager1->last_name = 'Arora';
   $manager1->reportee_ids = array(2, 3, 43, 21);

   $manager1->about_me();

   echo $info;
?>

 

Output

$./overriding_demo.php 

first_name : Vadiraj
last_name : Arora
designation : Engineering Manager
Reportee ids : Array
(
    [0] => 2
    [1] => 3
    [2] => 43
    [3] => 21
)

 

As you see the definition of Manager class,

a.   Property $designation is redefined (overridden)

b.   Method about_me is redefined (Overridden).

 


 

 

Previous                                                    Next                                                    Home

Thursday, 11 January 2018

Kotlin: Overriding conflict while implementing interfaces

If you are implementing more than one interface and those interfaces have same method signatures, then you will end up in conflict scenario.

HelloWorld.kt
interface Interface1{
 fun welcomeMessage(name : String){
  println("Welcome $name")
 }
}

interface Interface2{
 fun welcomeMessage(name : String){
  println("Good Morning $name")
 }
}

class MyClass : Interface1, Interface2{

 
}

When you try to compile above program, you will end up in below error.

ERROR: Class 'MyClass' must override public open fun welcomeMessage(name: String): Unit defined in Interface1 because it inherits multiple interface methods of it (13, 1)

How to resolve above error?
By overriding the function welcomeMessage in MyClass, you can get rid of above error.

class MyClass : Interface1, Interface2 {
 override fun welcomeMessage(name: String) {
  println("Hello $name")
 }

}

Find the below working application.


HelloWorld.kt
interface Interface1 {
 fun welcomeMessage(name: String) {
  println("Welcome $name")
 }
}

interface Interface2 {
 fun welcomeMessage(name: String) {
  println("Good Morning $name")
 }
}

class MyClass : Interface1, Interface2 {
 override fun welcomeMessage(name: String) {
  println("Hello $name")
 }

}

fun main(args: Array<String>) {
 var obj = MyClass()
 obj.welcomeMessage("krishna")
}

Output
Hello Krishna

How can I call interface method implementations from class?
By using super keyword, you can call interface method implementations from a class.

Ex
class MyClass : Interface1, Interface2 {
         override fun welcomeMessage(name: String) {
                 super<Interface1>.welcomeMessage(name)
                 super<Interface2>.welcomeMessage(name)
         }
}

Find the below working application.

HelloWorld.kt

interface Interface1 {
 fun welcomeMessage(name: String) {
  println("Welcome $name")
 }
}

interface Interface2 {
 fun welcomeMessage(name: String) {
  println("Good Morning $name")
 }
}

class MyClass : Interface1, Interface2 {
 override fun welcomeMessage(name: String) {
  super<Interface1>.welcomeMessage(name)
  super<Interface2>.welcomeMessage(name)
 }
}

fun main(args: Array<String>) {
 var obj = MyClass()
 obj.welcomeMessage("krishna")
}

Output

Welcome krishna
Good Morning Krishna


Previous                                                 Next                                                 Home

Saturday, 6 January 2018

Kotlin: Overriding methods

By using ‘override’ keyword, you can override the methods of base class. By default all the methods in a class are final (not overridable), you can make them overridable by using ‘open’ keyword’.

Override.kt
open class BaseClass{
 open fun sayHello(){
  println("******Hello World******")
 }
}

class DerivedClass : BaseClass(){
 override fun sayHello(){
  println("@@@@Hello World@@@@@")
 }
}
fun main(args: Array<String>) {
 var obj = DerivedClass()
 
 obj.sayHello()
 
}


Output
@@@@Hello World@@@@@


As you observe above snippet, DerivedClass inhrites from BaseClass. sayHello() method of DerivedClass override the sayHello() method of BaseClass using override keyword.

A method defined with the keyword ‘override’ is itself open, so the child classes of the DerivedClass, can override this method.


Override.kt
open class BaseClass {
 open fun sayHello() {
  println("******Hello World******")
 }
}

open class DerivedClass : BaseClass() {
 override fun sayHello() {
  println("@@@@Hello World@@@@@")
 }
}

class ChildDerivedClass : DerivedClass() {
 override fun sayHello() {
  println("####Hello World####")
 }
}

fun main(args: Array<String>) {
 var obj = ChildDerivedClass()

 obj.sayHello()

}

Output
####Hello World####

If you want to prohibit the re-overriding, use the keyword final.

Ex
open class DerivedClass : BaseClass() {
         final override fun sayHello() {
                 println("@@@@Hello World@@@@@")
         }
}


Override.kt
open class BaseClass {
 open fun sayHello() {
  println("******Hello World******")
 }
}

open class DerivedClass : BaseClass() {
 final override fun sayHello() {
  println("@@@@Hello World@@@@@")
 }
}

class ChildDerivedClass : DerivedClass() {
 override fun sayHello() {
  println("####Hello World####")
 }
}

fun main(args: Array<String>) {
 var obj = ChildDerivedClass()

 obj.sayHello()

}

When you try to compile above program, kotlin compiler throws below error.

'sayHello' in 'DerivedClass' is final and cannot be overridden





Previous                                                 Next                                                 Home

Thursday, 4 January 2018

Kotlin: Inheritance

Inheritance is the concept of re usability. Object of one class can get the properties and methods of object of another class by using inheritance.

By using inheritance, you can create new class by extending the existing class. The new class is called derived class and the existing class is called base class.



Example
open class BaseClass{

}

class DerivedClass : BaseClass{

}


By default, all the classes in kotlin are final. To make these class inheritable, you should use the keyword ‘open’.


Let’s see inheritance feature by an example. In every organization, there are two kinds of employees.
a.   Permanent Employees
b.   Contract Employees

Both the permanent and contract employees share properties like firstName, lastName and id. Where as contract employees has separate payroll company. We can place these common properties (firstName, lastName and id) in separate class Employee and make the classes PermanentEmployee and ContractEmployee inherit these properties from the common base class Employee.

open class Employee {

}

class PermanentEmployee : Employee {

}

class ContractEmployee : Employee {

}

Find the below working application.


Inheritance.kt
open class Employee {
 var firstName: String = ""
 var lastName: String = ""
 var id: String = ""

 constructor(firstName: String, lastName: String, id: String) {
  this.firstName = firstName
  this.lastName = lastName
  this.id = id
 }

 open fun getEmployee(): String {
  return "firstName : $firstName, lastName: $lastName, id: $id"
 }

}

class PermanentEmployee : Employee {
 var healthInsuranceNumber = ""
 var salary: Double = 0.0

 constructor(firstName: String, lastName: String, id: String, healtInsuranceNumber: String, salary: Double) : super(firstName, lastName, id) {
  this.healthInsuranceNumber = healtInsuranceNumber
  this.salary = salary
 }

 override fun getEmployee(): String {
  return super.getEmployee() + ", healthInsuranceNumber: $healthInsuranceNumber, salary: $salary"
 }

}

class ContractEmployee : Employee {
 var payRollCompany = "ABC"

 constructor(firstName: String, lastName: String, id: String, payRollCompany: String) : super(firstName, lastName, id) {
  this.payRollCompany = payRollCompany
 }

 override fun getEmployee(): String {
  return super.getEmployee() + ", payRollCompany: $payRollCompany"
 }
}


fun main(args: Array<String>) {
 var emp = PermanentEmployee("krishna", "Gurram", "123", "health3425", 56789.01)

 println(emp.getEmployee())
}


Output
firstName : krishna, lastName: Gurram, id: 123, healthInsuranceNumber: health3425, salary: 56789.01

constructor(firstName: String, lastName: String, id: String, healtInsuranceNumber: String, salary: Double) : super(firstName, lastName, id)
If super class don’t have default constructor, then all the sub class constructors must call the super class constructor explicitly.

By default, all the functions and classes are not inheritable (final), to make them inheritable, you should use the keyword ‘open’.

open class Employee {

         open fun getEmployee(): String {
                 return "firstName : $firstName, lastName: $lastName, id: $id"
         }

}

To override a function of super class, you should use override keyword.

class PermanentEmployee : Employee {

         override fun getEmployee(): String {
                 return super.getEmployee() + ", healthInsuranceNumber: $healthInsuranceNumber, salary: $salary"
         }

}

Important Points
a.   If the class has a primary constructor, the base type can (and must) be initialized right there, using the parameters of the primary constructor.


b.   If the class has no primary constructor, then each secondary constructor has to initialize the base type using the super keyword, or to delegate to another constructor which does that. Note that in this case different secondary constructors can call different constructors of the base type:


Previous                                                 Next                                                 Home

Friday, 21 February 2014

final Classes and Methods

final methods
If a method declared as final, then it can't be overridden by sub class.

Example
class SuperClass{
 final void print(){
 }
}

class SubClass extends SuperClass{
 void print(){
 }
} 

SubClass trying to override the method print() which is final. So when trying to compile the program, SubClass, then compiler throws the below error.
 SubClass.java:2: error: print() in SubClass cannot override print() in SuperClass
    void print(){
    ^
    overridden method is final
    1 error

Same is applicable to static classes also.
class SuperClass{
 final static void print(){
 }
}
 

class SubClass extends SuperClass{
 static void print(){
 }
}

When you tries to compile the SubClass.java, compiler throws the below error.
    SubClass.java:2: error: print() in SubClass cannot override print() in SuperClass
    static void print(){
    ^
    overridden method is static,final
    1 error

final classes
Any class which is declared as final, can't be extended. Try to extend a final class causes a compiler error.

Example
final class SuperClass{

}

class SubClass extends SuperClass{

}


When you tries to compile the SubClass.java, compiler throws the below error.

SubClass.java:1: error: cannot inherit from final SuperClass
    class SubClass extends SuperClass{
    ^
    1 error

Some Points to Remember

1. Both the private and final methods can't be overridden.
Example
class SuperClass{ 
 private void print(){ 
  System.out.println("I am super class"); 
 } 
}
   
class SubClass extends SuperClass{
 void print(){
  System.out.println("I am sub class");
 }

 public static void main(String args[]){
  SuperClass obj = new SubClass();
  obj.print();
 }
}


When you tries to compile the SubClass.java, compiler throws the below error.

 SubClass.java:8: error: print() has private access in SuperClass
            obj.print();
            ^
            1 error
         
2. Can I make private method as final ?
Since private already implies that a subclass may not override a method, declaring a private method to be final is redundant. It won't cause any problem to your program, Program compiles fine.


Final Variables                                                 Abstract methods and Abstract classes                                                 Home

Wednesday, 19 February 2014

Covariant return type

An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

Example
class Animal{
 String name;

 void setName(String name){
  this.name = name;
 }

 Animal getAnimal(){
  return this;
 }
}

class Tiger extends Animal{
 String name;

 void setName(String name){
      this.name = name;
 }

 Tiger getAnimal(){
      System.out.println("I am tiger and my Name is " + name);
      return this;
 }

 public static void main(String args[]){
      Animal anim = new Tiger();
      anim.setName("Aslam");
      anim.getAnimal();
 }
}

Output
I am tiger and my Name is Aslam

As you see the Tiger.java, the return type for the getAnimal() is Tiger, which is a sub class of “Animal”, so the method overridden.

Some points to Remember

1. Covariant types are applicable for reference types, not for primitives
class Animal{
 int getAnimal(){
  return 0;
 }
}

class Tiger extends Animal{
 byte getAnimal(){
  return 0;
 }
}
     
When you tries to compile the class “Tiger”, compiler throws below error
Tiger.java:2: error: getAnimal() in Tiger cannot override getAnimal() in Animal
byte getAnimal(){
^
return type byte is not compatible with int
1 error


Method Overriding                                                 Hiding methods                                                 Home

Overriding Methods

A subclass has the same instance method signature like the super class instance method is called overriding.

Example
class Animal{
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 void print(){
  System.out.println("I am Tiger");
 }
}

As you observe, the classes Animal and Tiger has the same method signature print(). So print method in the class Tiger overrides the method in the class Animal.

Dynamic Method Dispatch
It is a mechanism, where a call to the overridden method is resolved at run time. It is also called as run time polymorphism.

Take the same examples Animal and Tiger.
class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.print();
 }
}

Output
I am Tiger

As you see the statement
     Animal anim1 = new Tiger();

An object of the Tiger class is assigned to the Animal reference variable. This is completely correct in Java. We can assign a subclass object to super class reference variable.

When the program calls the print(), then at run time JVM checks, the actual object pointed by the reference variable and calls the respective method of the actual object. So it calls the print method in the Tiger class.

Modifiers
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

Some points to Remember
1. Is run time polymorphism applicable to static methods also ?
No, static methods can't be overridden, they just hide the static method of the super class.

2. Is the instance variables overridden ?
No
class Animal{
 String str = "Animal";
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 void print(){
  System.out.println("I am Tiger");
 }
}
    
class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.print();
  System.out.println(anim1.str);
 }
}
   
Output
I am Tiger
Animal

If the instance variables are overridden, then the output should print the message “Tiger”. I.e, instance variables are just hide the instance variables of super class, these can't be overridden.

3. Can I apply static modifier to the subclass overriding method?
No, compiler throws an error.
 
 Example       
class Animal{
 String str = "Animal";
 
 void print(){
 System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 
 static void print(){
  System.out.println("I am Tiger");
 }
}
   
When tries to compile the Tiger class, below error thrown.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
static void print(){
^
overriding method is static
1 error

4. What is wrong with the below program ?    
class Animal{
 String str = "Animal";
 
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 
 private void print(){
  System.out.println("I am Tiger");
 }
}


When you tries to compile the above program, compiler throws the “Weaker access specifier error”

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
private void print(){
^
attempting to assign weaker access privileges; was package
1 error

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

5. What is the difference between static binding and Dynamic binding ?
Static binding occurs at compile time, where as Dynamic binding at run time. Dynamic method dispatch is an example for Dynamic binding.

6. What is wrong with the below program ?
class Animal{
 String str = "Animal";
 
 void print(){
  System.out.println("I am animal");
 }
}
  
class Tiger extends Animal{
 String str = "Tiger";

 void print()throws Exception{
  System.out.println("I am Tiger");
 }
}

The overriding method cannot throw any exceptions that are not thrown by the overridden method.

When you tries to compile the above program compiler throws the below error.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
void print()throws Exception{
^
overridden method does not throw Exception
1 error

7. Is the constructors inherited ?
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses.

8. When a subclass object assigned to super class reference variable, then the reference variable can call the methods which are defined in the super class, trying to call the methods which are not defined in super class cause the compile time error.

Example
class Animal{
 void print()throws Exception{
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 void print(){
  System.out.println("I am Tiger");
 }

 void show(){
  System.out.println("I am show method");
 }
}

class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.show();
 }
}
    
When you are trying to compile the program, below error thrown, since the reference variable of class Animal, “anim1” trying to call the method “show: which is not defined in the class “Animal”.

DynamicMethodDispatchEx.java:5: error: cannot find symbol
anim1.show();
^
symbol: method show()
location: variable anim1 of type Animal
1 error

9. Can I specify weaker access specifier to the overriding method in the sub class ?
No


Multi path inheritance                                                 Covariant return type                                                 Home