Upcasting & Downcasting in Java

Duration: 24 min

This video lesson is available to enrolled students.

Return to /learn/ASRB-ICAR-T3-T4-INFORMATION-TECHNOLOGY-PRELIMS-MAINS/oops-with-c-java/oops-with-java/polymorphism/asset-upcasting-downcasting-in-java after enrolling

Inside: a video lesson and guided study material.

Module outline

  1. Prelims: General Knowledge: Physics Chemistry Biology History Geography Polity Indian Economy Static General Knowledge GK- Current Affairs Environment
  2. Prelims: General English: Vocabulary Noun Pronoun Adjectives Preposition Articles Direct and Indirect Speech Tenses Conjunction Subject Verb Agreement (Verb Noun Agreement) Modals Sentence Re-arrangements (Para Jumbles) (Narrative Sequencing) Sentence Correction (Error Correction) Sentence Completion (Fill in the blanks) Comprehension / Reading Comprehension / Unseen Passages (Critical Reasoning) (Paragraph Questions) Cloze Test (Cloze Passage) Verbal Analogy (Word Based Analogy) Sentence Construction Adverb Verb
  3. Prelims: Quantitative Aptitude: Percentage Ratio and Proportion (Ratios) HCF LCM Divisibility Rules Average Sequence and Series (Series) Number System Powers and Exponents (Surds and Indices) Algebra Profit and Loss Simple Interest and Compound Interest Time and Work Pipe and Cistern Speed Time and Distance Mixture and Alligation Mensuration and Geometry Age Problems Partnership Statistics Data Interpretation Arithmetic
  4. Prelims: General Agriculture: Agriculture in India and Tripura Natural Resource Management Fundamentals of Crop Production Horticulture Crop Improvement Crop Protection Social Science
  5. IT Mains: Operating System: Introduction to OS Process Management CPU Scheduling Process Synchronization Threads & Process Creation Deadlock Memory Management Virtual Memory Disc Scheduling File Management Distributed Systems
  6. IT Mains: Computer Networking: Introduction to CN DLL: Access Control DLL: Flow Control DLL: Error Control Data Link Layer - Ethernet Net Layer: IPv4 & Proto Net Layer: IP Addressing Net Layer:Routing Protocol Transport Layer Services TL: Congestion & UDP Application Layer Hardware Basics Network Security
  7. IT Mains: DBMS: Basics of DBMS ER Diagram Relational Model & Functional Dependencies Keys & Integrity Constraints Normalization (1NF - BCNF) Decomposition Properties & 4NF Relational Algebra SQL Relational Calculus Transaction Management Concurrency Control Database Recovery Big Data Systems Database Security & Authorization Enhanced Data Models NoSQL
  8. IT Mains: Software Engineering: Fundamentals of Software Engineering Software Requirements and Quality Assurance Software Design, Estimation and Metrics Software Testing Software Maintenance and Configuration Management
  9. IT Mains: Data Structures & Algorithms: Introduction to DS Array Stack Queue Linked List Tree Graphs Hashing Algorithm Analysis Time Complexity Analysis Sorting Algorithms
  10. IT Mains: OOPS with C++ & Java: C Fundamentals OOPS with C++ Java Fundamentals Array, String, IO & References OOPS with Java Generic & Collections Multithreading File Handling & I/O
  11. IT Mains: Python: Introduction to Python Tokens, Variables, Data Types, I/O Operators & Expressions Control Flow & Looping Collections & Strings Functions & Modules
  12. IT Mains: Website Development: Website, Browser & Services Internet Fundamentals Web Design & Development Protocols & Services Web Publishing & Hosting Server Side & Security Emerging Technologies HTML Basics HTML5 CSS JavaScript-Basics .Net Programming PHP
  13. IT Mains: Mobile App Development: Mobile Computing Multimedia
  14. IT Mains: Linux / Windows Server Admin: Unix OS Linux OS
AI summary & chapters

AI Summary

An AI-generated summary of this video lecture.

This lecture introduces Dynamic Method Dispatch in Java, defining it as the runtime selection of an overridden method when a parent-class reference refers to a child-class object. The instructor uses a Parent/Child example with a show() method, showing that Parent p = new Child(); p.show(); prints Child because the actual object type determines method execution. The lesson then transitions to Upcasting, where a child object is assigned to a parent reference automatically, such as Animal a = new Dog();. In this case, only methods available in the parent class can be called: a.sound() is valid, while a.bark() causes a compile-time error because bark() is not available in Animal. Finally, the lecture covers Downcasting, where a parent reference is explicitly cast to a child type, such as Dog d = (Dog) a;. Downcasting works when the actual object is a Dog, allowing d.bark() to run, but fails with a ClassCastException when the actual object is an Animal, as in Animal a = new Animal(); Dog d = (Dog) a;. The video emphasizes the distinction between compile-time type checking and runtime object type, using code, diagrams, and console output to illustrate valid and invalid method calls.

Chapters

  1. 0:00 – 2:00 00:00-02:00

    The video introduces Dynamic Method Dispatch, displayed on screen as the mechanism by which Java selects an overridden method at runtime. It states that this occurs when a parent-class reference refers to a child-class object. A code example shows class Parent with show() printing Parent and class Child extends Parent with @Override show() printing Child. The statement Parent p = new Child(); p.show(); is shown, with console output reading Output: Child. A diagram labels Parent p = new Child(); as a Reference of Parent type and Actual object of Child type, leading to a Child Object box where show() -> 'Child' and p.show(); are shown. A yellow note states that the actual object (Child) decides which method to call, equating Dynamic Method Dispatch with Run-Time Polymorphism.

  2. 2:00 – 5:00 02:00-05:00

    The instructor continues explaining Dynamic Method Dispatch using the same Parent/Child example. The slide repeats the definition and the line It occurs when a parent-class reference refers to a child-class object. The Main.java editor shows class Parent with show() printing Parent, class Child extends Parent with @Override show() printing Child, and main() containing Parent p = new Child(); and p.show();. The console panel reads Output: Child. The right-side diagram again labels Parent p = new Child(); with Reference of Parent type and Actual object of Child type, leading to a Child Object box showing show() -> 'Child' and p.show();. The instructor uses hand-drawn annotations to clarify the relationship between the reference type and the actual object type, emphasizing that the actual object determines which overridden method is executed at runtime.

  3. 5:00 – 10:00 05:00-10:00

    The lecture remains focused on Dynamic Method Dispatch, with the slide showing the definition and the Parent/Child code example. Red handwriting boxes Parent p = new Child(); and crosses out P -> P and C -> X, highlighting the valid parent-to-child reference assignment. The Main.java editor shows class Parent with show() printing Parent, class Child extends Parent with @Override show() printing Child, and main() containing Parent p = new Child(); and p.show();. The right-side diagram labels Parent p = new Child(); as Reference of Parent type and Actual object of Child type, with a Child Object box showing show() -> 'Child', p.show();, and a yellow note stating Actual object (Child) decides which method to call (Dynamic Method Dispatch = Run-Time Polymorphism). The instructor points to and annotates the text parent-class reference refers to a child-class object, reinforcing the core rule of dynamic method dispatch.

  4. 10:00 – 15:00 10:00-15:00

    The lesson transitions from Dynamic Method Dispatch to Upcasting. The instructor explains that upcasting means assigning a child-class object to a parent-class reference, done automatically by Java. An Animal/Dog code example is introduced, showing class Animal with sound() and class Dog extends Animal overriding sound() and adding bark(). The main method runs Animal a = new Dog(); a.sound();. A diagram labels Parent Class: Animal, Actual object of child type (Dog), and Animal a = new Dog();, marking a.sound() with a green check and a.bark() with a red X labeled Not available in Animal. The console output shows Dog Barks, demonstrating that the overridden sound() method in Dog is called at runtime, while the child-specific bark() method cannot be accessed through the parent reference.

  5. 15:00 – 20:00 15:00-20:00

    The lecture continues with the Up-Casting slide, which states that upcasting means assigning a child-class object to a parent-class reference, done automatically (implicitly) by Java. The code panel shows class Animal with sound() and class Dog extends Animal overriding sound() and adding bark(), with Main running Animal a = new Dog(); a.sound();. The diagram labels Parent Class: Animal, Actual object of child type (Dog), and Animal a = new Dog();, marking a.sound() with a green check and a.bark() with a red X (Not available in Animal). The output reads Dog Barks. The instructor emphasizes that only methods available in the parent class can be called through a parent reference, even though the actual object is a Dog. This section reinforces the compile-time type checking rule: the reference type determines which methods are accessible, while the actual object type determines which overridden method is executed.

  6. 20:00 – 24:29 20:00-24:29

    The video explains Downcasting, which involves converting a parent-class reference into a child-class reference using an explicit cast. The slide titled Downcasting: Why and Warning presents two scenarios. In the first, Animal a = new Dog(); is upcasting, followed by Dog d = (Dog) a; as downcasting, and d.bark(); is valid because the actual object is a Dog. In the second, Animal a = new Animal(); is shown, and attempting Dog d = (Dog) a; causes a runtime error because the actual object is an Animal, not a Dog. The instructor highlights the ClassCastException warning in the failed downcast example. Red circles and arrows emphasize key parts of the code and diagrams, comparing the successful and failed scenarios to illustrate why downcasting works only when the actual object type matches the target child type.

The lecture progresses from Dynamic Method Dispatch to Upcasting and then Downcasting, building a coherent understanding of Java's runtime polymorphism and type casting. Dynamic Method Dispatch is established as the runtime selection of an overridden method when a parent reference points to a child object, demonstrated with Parent p = new Child(); p.show(); printing Child. Upcasting is then introduced as the automatic assignment of a child object to a parent reference, such as Animal a = new Dog();, where only parent-class methods are accessible at compile time, so a.sound() is valid but a.bark() is not. Downcasting is presented as the explicit reverse operation, Dog d = (Dog) a;, which allows access to child-specific methods like bark() only when the actual object is indeed a Dog. The critical distinction is between compile-time type checking, governed by the reference type, and runtime method execution, governed by the actual object type. The ClassCastException example underscores the danger of downcasting when the actual object does not match the target type. Together, these concepts form the foundation for understanding polymorphism, inheritance, and safe type conversion in Java.

Loading lesson…