Upcasting & Downcasting in Java

Duration: 24 min

This video lesson is available to enrolled students.

Return to /learn/RPSC-PROGRAMMER/paper-2-programming-language-java/oops-with-java/polymorphism/asset-upcasting-downcasting-in-java after enrolling

Inside: a video lesson and guided study material.

Module outline

  1. Paper 1 | Reasoning Test: Series (Number and Letter Series) (Numerical Relations and Reasoning), Coding Decoding, Data Sufficiency, Syllogisms, Deductive and Inductive Reasoning (Logical Deduction and Induction) (Prepositional Reasoning), Seating Arrangements, Blood Relations, Puzzle Solving (Puzzles), Venn Diagram, Analogy, Ranking, Order and Sequence, Non Verbal Reasoning (Spatial Aptitude) (Spatial Reasoning) (Visual Reasoning), Selection Decision Table (Decision Making), Logical Sequence Of Words, Cubes & Dices, Analytical Reasoning (Counting Figures Reasoning), Calendar, Alphabet and Word Tests, Numerical Reasoning, Number System, Averages, Mixtures and Alligation, Percentages, Series Completion, Analogy and Classification, Patterns in Two-Dimensional Figures, Coding and Decoding, Mathematical Operations, Direction Sense, Algebra, Logical Deduction and Induction, Syllogisms and Venn Diagrams, Critical Reasoning, Order, Ranking and Sequence, Reading Comprehension, Profit, Loss and Discount, Constraint Puzzles, Speed, Time and Distance, Traverse Surveying, Ratio and Proportion, Time and Work, Mensuration, Permutations and Combinations, Clocks and Calendars, Data Interpretation, Assembling and Grouping of Shapes, Transformation of Shapes, Three-Dimensional Patterns and Visualization, Cubes and Dice, Vocabulary, Blood Relations, Data Sufficiency
  2. Paper 1 | Numerical Analysis: Number System, HCF LCM, Percentage, Ratio and Proportion (Ratios), Average, Sequence and Series (Series), Powers and Exponents (Surds and Indices), Algebra, Statistics, Data Interpretation, Mental Ability, Arithmetic, Logarithm, Profit and Loss, Simple Interest and Compound Interest, Speed Time and Distance, Mixture and Alligation, Mensuration and Geometry, Permutation and Combination, Probability, Sequences and Series, Powers, Surds and Logarithms, Subject-Verb Agreement, Sentence Completion, Geometry, Sentence Structure and Correction, Data Sufficiency, Trigonometry, Measurement and Quantity Take-Off, Signal Space and Optimum Detection, Probability, Statistics, Algebra, Time and Work, Speed, Time and Distance, Data Interpretation, Graph Theory, Combinatorics
  3. Paper 1 | General Knowledge: State Wise GK, History, Geography, GK- Current Affairs, Static General Knowledge, Polity, Indian Economy
  4. Paper 1 | DBMS: Basics of DBMS, ER Diagram, Relational Model & Functional Dependencies, Keys & Integrity Constraints, Normalization (1NF - BCNF), Decomposition Properties & 4NF, File Organization & Indexing, Relational Algebra, SQL, Transaction Management, Concurrency Control, Relational Calculus, Database Security & Authorization, Database Recovery
  5. Paper 1 | Data Communication & Network: Introduction to CN, Data Communication, DLL: Access Control, DLL: Flow Control, DLL: Error Control, DLL: Framing, Data Link Layer - Ethernet, Net Layer: IPv4 & Proto, Net Layer: IP Addressing, Net Layer:Routing Protocol, Transport Layer Services, TL: Congestion & UDP, Application Layer, Network Security, Security in Mobile and Wireless Computing, Input Output Organisation, File Management, Hardware Basics, Terms & Abbreviations, Protocols & Services, Network Access Technologies, Cyber Safety and Security, Basics of COA
  6. Paper 2 | System Analysis & Design: Fundamentals of Systems and Information Systems, SDLC and Development Approaches, Fundamentals of Software Engineering, Software Requirements and Quality Assurance, Software Documentation and Software Requirements Specification (SRS), SDD and Quality Assurance, Software Design, Estimation and Metrics, Software Testing, Software Maintenance and Configuration Management, Security, Risk Management & Maintenance, extras
  7. Paper 2 | Programming Language (Java): Java Fundamentals, OOPS with Java, Array, String, IO & References, Generic & Collections, Multithreading, Java, Miscellaneous, Control Flow, OOPS with C++, Stack, C Fundamentals, Arrays & Pointers, Object Oriented Technology, Control Flow & Looping, Introduction to Python
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…