Chapter 10 Inheritance and Polymorphism

Similar documents
SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

AP Computer Science Java Subset

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Java Interview Questions and Answers

Java Programming Language

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Inheritance, overloading and overriding

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

CS 111 Classes I 1. Software Organization View to this point:

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

CS506 Web Design and Development Solved Online Quiz No. 01

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

D06 PROGRAMMING with JAVA

Java Application Developer Certificate Program Competencies

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Part I. Multiple Choice Questions (2 points each):

Fundamentals of Java Programming

Description of Class Mutation Mutation Operators for Java

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

History OOP languages Year Language 1967 Simula Smalltalk

What are exceptions? Bad things happen occasionally

The Interface Concept

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 13 - Inheritance

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Object-Oriented Programming: Polymorphism

Lecture J - Exceptions

CS193j, Stanford Handout #10 OOP 3

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

D06 PROGRAMMING with JAVA

Compile-time type versus run-time type. Consider the parameter to this function:

public static void main(string[] args) { System.out.println("hello, world"); } }

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Programmation 2. Introduction à la programmation Java

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Programming Languages Featherweight Java David Walker

Software Construction

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Object-Oriented Programming Lecture 2: Classes and Objects

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

Using Inheritance and Polymorphism

CIS 190: C/C++ Programming. Polymorphism

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Abstract Class & Java Interface

Teach Yourself Java in 21 Minutes

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Konzepte objektorientierter Programmierung

University of Twente. A simulation of the Java Virtual Machine using graph grammars

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

15-214: Principles of Software Construction 8 th March 2012

Chapter 2 Introduction to Java programming

Java from a C perspective. Plan

Moving from CS 61A Scheme to CS 61B Java

C++ INTERVIEW QUESTIONS

1. Properties of Transactions

11 November

Java (12 Weeks) Introduction to Java Programming Language

Basic Programming and PC Skills: Basic Programming and PC Skills:

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Part 3: GridWorld Classes and Interfaces

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Application-only Call Graph Construction

JAVA INTERVIEW QUESTIONS

Chapter 1 Java Program Design and Development

Inheritance in Programming Languages

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Introducing Variance into the Java Programming Language DRAFT

Unit Testing and JUnit

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

ECE 122. Engineering Problem Solving with Java

Object Oriented Software Design

Remote Method Invocation

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

LAB4 Making Classes and Objects

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Dennis Olsson. Tuesday 31 July

Transcription:

Chapter 10 Inheritance and Polymorphism 1. Inheritance: derive a new class from an existing class a. The new class is called a subclass, or child class b. The existing class is called a superclass, or parent class 2. Unlike properties and methods, the constructors of a superclass are not inherited in the subclass. They can be invoked only from the constructors of the subclasses, using the keyword super. (must be the first statement in the constructor) 3. If none of the superclass s constructor is invoked explicitly, the compiler implicitly invokes the superclass s no-arg constructor. 4. Method overriding a. Using the same method header as in its superclass b. The private and static methods cannot be overridden 5. Method overloading a. Using the same method name b. Overloaded constructors 6. Object is the superclass of every other class in Java. 7. A class defines a type. A type defined by a subclass is called a subtype and a type defined by its superclass is called a supertype. 8. Polymorphism: An object of a subtype can be used wherever its supertype value is required. 9. Dynamic binding: when invoking an instance method from a reference variable, the actual type of the variable decides which implementation of the method is used at runtime. 10. Type casting a. It is always possible to cast an instance of a subclass to a variable of a superclass (is-a relationship) b. When casting an instance of a superclass to a variable of its subclass, explicit casting must be used. 11. You can use objectname instanceof classname to test whether an object is an instance of a class. 12. protected modifier 13. You can use final modifier to indicate that a class is final and cannot be a parent class and to indicate that a method is final and cannot be overridden. Exercises: 1. What is the output of the following code? class A{ public A(){

System.out.println( A s no-arg constructor is invoked ); class B extends A{ public class C{ B b = new B(); 2. What is wrong in the following code? class A{ public A(int x){ class B extends A{ public B(){ public class C{ B b = new B(); 3. True or false? a. A subclass is a subset of a superclass. b. When invoking a constructor from a subclass, its superclass s no-arg constructor is always invoked. c. You can override a private method defined in a superclass. d. You can override a static method defined in a superclass. e. A protected data or method can be accessed by any class in the same package. f. A protected data or method can be accessed by any class in different packages. g. A final class can have instance.

h. A final method can be overridden. i. You can always successfully cast an instance of a superclass to a subclass. 4. Identify the problems in the following classes? public class Circle{ private double radius; public Circle(double radius){ radius = radius; public double getradius(){ return radius; public double getarea(){ return radius*radius*math.pi; class B extends Circle{ private double length; B(double radius, double length){ Circle(radius); length = length; public double getarea(){ return getarea()*length;

5. How do you explicitly invoke a superclass s constructor from a subclass? 6. How do you invoke an overridden superclass method from a subclass? 7. If a method in a subclass has the same signature as a method in its superclass with the same return type, is the method overridden or overloaded? 8. If a method in a subclass has the same signature as a method in its superclass with a different return type, is the method overridden or overloaded? 9. If a method in a subclass has the same name as a method in its superclass with different parameter types, is the method overridden or overloaded? 10. Show the output of following program: public class Test{ public static void main(string[] args) { A a = new A(3); class A extends B{ public A(int t){ System.out.println( A s constructor is invoked. ); class B{ public B(){ System.out.println( B s constructor is invoked. ); 11. Assume Circle extends from the class GeometricObject, answer the following questions: Circle circle = new Circle(); GeometricObject object1 = new GeometricObject(); a. True or false? i. circle instanceof GeometricObject ii. object1 instanceof GeometricObject iii. circle instanceof Circle iv. object1 instanceof Circle b. Can the following be compiled? i. object1 = circle; ii. circle = object1; iii. circle = (Circle)object1;

12. What modifier should you use on a class so that a class in the same package can access it, but a class in a different package cannot access it? 13. What modifier should you use so that a class in a different package cannot access the class, but its subclasses in any package can access it? 14. In the code below, classes A and B in the same package. public class A{? int i;? void m(){ ; public class B extends A{ public void m1(string[] args) { System.out.println(i); m(); a. If the question marks are replaced by blanks, can class B be complied? b. If the question marks are replaced by private, can class B be complied? c. If the question marks are replaced by protected, can class B be complied? d. If classes A and B in different packages, answer above a, b, c questions again. 15. How do you prevent a class from being extended? How do you prevent a method from being overrident? Chapter 11 Exception Handling 1. Exception handling enables a method to throw an exception to its caller. Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and modify. 2. A Java exception is an instance of a class derived from java.lang.throwable. Java provides a number of predefined exception classes, such as Error, Exception, RuntimeException, ClassNotFoundException, NullPointerException, and ArithmeticException. You can also define your own exception class by extending Exception. 3. Exceptions occur during the execution of a method. RuntimException and Error are unchecked exceptions; all other exceptions are checked. 4. For checked exception, when declaring a method, you have to declare a checked exception. You can declare multiple exceptions, separated by commas. a. The keyword for declaring an exception is throws b. The keyword for throwing an exception is throw. You cannot throw multiple exceptions in a single throw statement.

c. To invoke the method that declares checked exception, you must enclose the method call in a try block. When an exception occurs during the execution of the method, the catch block catches and handles the exception. 5. Various exception classes can be derived from a common superclass. If a catch block catches the exception objects of a superclass, it can also catch all the exception objects of the subclasses of that superclass. a. The order in which exceptions are specified in a catch block is important. b. Put a subclass type before a superclass type 6. The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or is caught. Exercises: 1. What RuntimeException will be following programs throw, if any? a. public class Test{ System.out.println(1 / 0); b. public class Test{ int[] list = new int[5]; System.out.println(list[5]); c. public class Test{ Object o = null; System.out.println(o.toString()); 2. Show the output of the following code. a. public class Test{ for(int i=0; i<2; i++){ System.out.print(i + ); try{ System.out.println(1 / 0); Catch (Exception ex){

b. public class Test{ try{ for(int i=0; i<2; i++){ System.out.print(i + ); System.out.println(1 / 0); Catch (Exception ex){ 3. What is the output of the following program? public class Test{ try{ int value = 30; if (value < 40) throw new Exception( value is too small ); catch(exception ex){ System.out.println(ex.getMessage()); System.out.println( Continue after the catch block. ); 4. Suppose that statement2 causes an exception in the following try-catch block: try{ statement1; statement2; statement3;

catch(exception1 ex1){ catch(exception2 ex2){ statement4; Answer the following questions: a. Will statement 3 be executed? b. If the exception is not caught, will statement4 be executed? c. If the exception is caught in the catch block, will statement4 be executed? d. If the exception is passed to the caller, will statement4 be executed? 5. Show the output of the following program. public class Test{ public static void main(string[] args) { try{ int[] list = new int[10]; System.out.println( list[10] is +list[10]); catch(arithmeticexception ex){ System.out.println( ArithmeticException ); catch(runtimeexception ex){ System.out.println( RuntimException ); catch(exception ex){ System.out.println( Exception ); 6. Correct a compile error in the following code: public void m(int value) { if(value < 40) throw new Exception( value is too small. );

Chapter 12 Abstract classes and Interfaces 1. Abstract classes are like regular classes with data and methods, but you cannot create instances of abstract classes using the new operator. 2. An abstract method cannot be contained in a non-abstract class. If a subclass of an abstracted superclass does not implement all the inherited abstracted methods of the superclass, the subclass must be defined abstract. 3. A subclass can be abstract even if its superclass is concrete. 4. An interface is a classlike construct that contains only constants and abstract methods, and no constructors. a. An abstract class can contain constants and abstract methods as well as variables and concrete methods. 5. A class can extend only one superclass but can implement one or more interfaces. 6. An interface can extend one or more interfaces. 7. The java.lang.comparable interface defines the compareto method. Exercises: 1. Which of the following classes definitions defines a legal abstract class? a. class A{ abstract void unfinished() { b. public class abstract A{ c. class A{ abstract void unfinished(); abstract void unfinished(); d. abstract class A{ protected void unfinished();

e. abstract class A{ abstract void unfinished(); f. abstract class A{ abstract int unfinished(); 2. Which of the following is a correct interface? a. interface A{ void print() {; b. abstract interface A extends I1, I2{ abstract void print() {; c. abstract interface A{ print(); d. interface A{ void print(); 3. True or false? a. An abstract class can be used just like a non-abstract class except that you cannot use the new operator to create an instance from the abstract class. b. If a class implements Comparable, the object of the class can invoke the compareto method. c. An abstract class can have instances created using the constructor of the abstract class.

d. An abstract class can be extended. e. A subclass of a nonabstract superclass cannot be abstract. f. A subclass cannot override a concrete method in a superclass to define it abstract. g. An abstract method must be nonstatic. h. An interface can have static methods. i. An interface can extend one or more interfaces. j. An interface can extend an abstract class. k. An abstract class can extend an interface. 4. What are the similarities and differences between abstract classes and interfaces?