Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
JS++ | Virtual Methods
Next article icon

JS++ | Virtual Methods

Last Updated : 30 Aug, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report

As we mentioned in the previous section, if we want runtime polymorphism, using casts can lead to unclean code.

By way of example, let's change our main.jspp code so that all our animals are inside an array. From there, we will loop over the array to render the animal. Open main.jspp and change the code to:

  import Animals;    Animal[] animals = [      new Cat("Kitty"),      new Cat("Kat"),      new Dog("Fido"),      new Panda(),      new Rhino()  ];    foreach(Animal animal in animals) {      if (animal instanceof Cat) {          ((Cat) animal).render();      }      else if (animal instanceof Dog) {          ((Dog) animal).render();      }      else {          animal.render();      }  }  

Now our code is even less elegant than our original code that just instantiated the animals, specified the most specific type, and called render().

However, this code can be massively simplified until it becomes elegant. In fact, we can reduce the 'foreach' loop down to one statement. The answer: virtual methods.

Virtual methods enable "late binding." In other words, the specific method to call is resolved at runtime instead of compile time. We don't need all the 'instanceof' checks, all the casts, and all the 'if' statements as we saw in the code above. We can achieve something much more elegant.

First, open Animal.jspp and change the 'render' method to include the 'virtual' modifier:

  external $;    module Animals  {      class Animal      {          protected var $element;            protected Animal(string iconClassName) {              string elementHTML = makeElementHTML(iconClassName);              $element = $(elementHTML);          }            public virtual void render() {              $("#content").append($element);          }            private string makeElementHTML(string iconClassName) {              string result = '<div class="animal">';              result += '<i class="icofont ' + iconClassName + '"></i>';              result += "</div>";              return result;          }      }  }  

Save Animal.jspp. That's the only change we need to make.

However, just making our method virtual isn't enough. In Cat.jspp and Dog.jspp, we are using the 'overwrite' modifier on their 'render' methods. The 'overwrite' modifier specifies compile-time resolution. We want runtime resolution. All we have to do is change Cat.jspp and Dog.jspp to use the 'override' modifier instead of the 'overwrite' modifier. For the sake of brevity, I will only show the change to Cat.jspp but you need to make the change to Dog.jspp as well:

  external $;    module Animals  {      class Cat : Animal      {          string _name;            Cat(string name) {              super("icofont-animal-cat");              _name = name;          }            override void render() {              $element.attr("title", _name);              super.render();          }      }  }  

That's it. All we had to do was change modifiers. Now we can finally edit main.jspp so there is only one statement inside the loop:

  import Animals;    Animal[] animals = [      new Cat("Kitty"),      new Cat("Kat"),      new Dog("Fido"),      new Panda(),      new Rhino()  ];    foreach(Animal animal in animals) {      animal.render();  }  

Compile your code and open index.html. Everything should work. Now we've been able to massively simplify our code and still get the expected behavior. Specifically, we reduced the code of our 'foreach' loop down from:

  foreach(Animal animal in animals) {      if (animal instanceof Cat) {          ((Cat) animal).render();      }      else if (animal instanceof Dog) {          ((Dog) animal).render();      }      else {          animal.render();      }  }  
To this:
  foreach(Animal animal in animals) {      animal.render();  }  

The reason we've been able to simplify our code so dramatically is because marking a method as 'virtual' signifies potential runtime polymorphism. Together with the 'override' modifier, the compiler knows we want late binding on the 'render' method so the "late" binding happens exactly when it's needed: the 'render' method will be resolved at runtime if and only when it needs to be resolved (inside the 'foreach' loop).


Next Article
JS++ | Virtual Methods

R

RogerPoon
Improve
Article Tags :
  • JS++

Similar Reads

    JS++ | Modules
    Modules provide a way to organize code and divide an application into smaller parts. For example, a personal computer can be divided into keyboard, mouse, and monitor "modules" that can be separately connected. Ideally, in modular design, we want our modules to be independently "re-usable." A PS/2 k
    4 min read
    JS++ | Fields and Methods
    Creating and Rendering an Animal Open 'src/Animals/Cat.jspp' and enter the following code: external $; module Animals { class Cat { void render() { var $element = $( """ <div class="animal"> <i class="icofont icofont-animal-cat"></i> </div> """ ); $("#content").append($elemen
    9 min read
    JS++ | The 'final' Modifier
    In the context of virtual methods discussed in the previous section, the 'final' modifier allows us to form an even more correct specification. When applied to overridden methods, the 'final' modifier allows us to specify that this method override is the last and cannot be further overridden. This p
    2 min read
    JS++ | Abstract Classes and Methods
    We have explored virtual methods and 'overwrite' (early binding) and 'override' (late binding) which allow us to define base implementations for a method and more specific implementations of the method in subclasses. However, what do we do if there is no relevant base implementation that makes sense
    3 min read
    JS++ | Subtype Polymorphism
    Subtyping describes type relationships, and subtype polymorphism enables operations defined for supertypes to be safely substituted with subtypes. Concretely, imagine the relation between a 'Cat' class and an 'Animal' class. (Remember: classes create data types in JS++.) In this case, within the con
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences