Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Similar documents
CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS1150 Principles of Computer Science Objects and Classes

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Chapter 11 Inheritance and Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods

Inheritance (continued) Inheritance

We are on the GUI fast track path

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

Chapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver {

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CS171:Introduction to Computer Science II. Li Xiong

CS-202 Introduction to Object Oriented Programming

Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017

CH. 2 OBJECT-ORIENTED PROGRAMMING

Inheritance and Polymorphism

Object Orientated Programming Details COMP360

Chapter 14 Abstract Classes and Interfaces

EKT472: Object Oriented Programming. Overloading and Overriding Method

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

Questions Answer Key Questions Answer Key Questions Answer Key

Generics. CSE260, Computer Science B: Honors Stony Brook University

Inheritance (Deitel chapter 9)

Inheritance. Transitivity

Java Classes, Objects, Inheritance, Abstract and Interfaces Recap

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Practice for Chapter 11

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

ITI Introduction to Computing II

Chapter 13 Abstract Classes and Interfaces

CSA 1019 Imperative and OO Programming

Chapter 8 Objects and Classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Object Oriented Programming

25. Generic Programming

Chapter 8 Objects and Classes

ITI Introduction to Computing II

OO Programming Concepts

ITI Introduction to Computing II

Programming 2. Inheritance & Polymorphism

Inheritance and Polymorphism

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Chapter 13 Abstract Classes and Interfaces

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CMSC 132: Object-Oriented Programming II

Abstract Classes Interfaces

Chapter 1: Introduction to Computers, Programs, and Java

Chapter 6: Inheritance

CS 113 PRACTICE FINAL

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Principles of Computer Science

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Polymorphism: Interfaces and Iteration. Fundamentals of Computer Science

Chapter 9 - Object-Oriented Programming: Inheritance

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Object Oriented Programming. Java-Lecture 11 Polymorphism

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

index.pdf January 21,

CS 251 Intermediate Programming Inheritance

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Java Fundamentals (II)

Reusing Classes. Hendrik Speleers

Computer Science II (20073) Week 1: Review and Inheritance

ITI Introduction to Computing II

COMP 250. inheritance (cont.) interfaces abstract classes

Class, Variable, Constructor, Object, Method Questions

Chapter 9 - Object-Oriented Programming: Polymorphism

ITI Introduction to Computing II

Chapter 9 Abstract Classes and Interfaces

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

AP CS Unit 6: Inheritance Notes

Inheritance (Part 2) Notes Chapter 6

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Lesson11-Inheritance-Abstract-Classes. The GeometricObject case

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Making New instances of Classes

Transcription:

Constructor Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance. 1

Superclasses and Subclasses -color: String -filled: boolean GeometricObject -datecreated: java.util.date +GeometricObject() +GeometricObject(color: String, filled: boolean) +getcolor(): String +setcolor(color: String): void +isfilled(): boolean +setfilled(filled: boolean): void +getdatecreated(): java.util.date +tostring(): String -radius: double +Circle() Circle +Circle(radius: double) +Circle(radius: double, color: String, filled: boolean) +getradius(): double +setradius(radius: double): void +getarea(): double +getperimeter(): double +getdiameter(): double +printcircle(): void The color of the object (default: white). Indicates whether the object is filled with a color(default: false). The date when the object was created. Creates a GeometricObject. Creates a GeometricObject with the specified color and filled values. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the datecreated. Returns a string representation of this object. -width: double -height: double +Rectangle() Rectangle +Rectangle(width: double, height: double) +Rectangle(width: double, height: double color: String, filled: boolean) +getwidth(): double +setwidth(width: double): void +getheight(): double +setheight(height: double): void +getarea(): double +getperimeter(): double GeometricObject CircleFromSimpleGeometricObject RectangleFromSimpleGeometricObject TestCircleRectangle Run 2

Are superclass s Constructor No. They are not inherited. Inherited? They are invoked explicitly or implicitly. Explicitly using the super keyword. A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked. 3

Superclass s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its superclass s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, public A() { is equivalent to public A() { super(); public A(double d) { // some statements is equivalent to public A(double d) { super(); // some statements 4

Using the Keyword super The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: To call a superclass constructor To call a superclass method 5

CAUTION You must use the keyword super to call the superclass constructor. Invoking a superclass constructor s name in a subclass causes a syntax error. Java requires that the statement that uses the keyword super appear first in the constructor. 6

Constructor Chaining Constructing an instance of a class invokes all the superclasses constructors along the inheritance chain. This is known as constructor chaining. public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 7

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); 1. Start from the main method public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 8

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); 2. Invoke Faculty constructor public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 9

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); 3. Invoke Employee s noarg constructor class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 10

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); 4. Invoke Employee(String) constructor class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 11

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); 5. Invoke Person() constructor class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 12

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); 6. Execute println class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 13

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); 7. Execute println class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 14

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); 8. Execute println class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 15

animation Trace Execution public class Faculty extends Employee { public static void main(string[] args) { new Faculty(); public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); 9. Execute println class Employee extends Person { public Employee() { this("(2) Invoke Employee s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); public Employee(String s) { System.out.println(s); class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); 16

Example on the Impact of a Superclass without no-arg Constructor Find out the errors in the program: public class Apple extends Fruit { class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); 17

Defining a Subclass A subclass inherits from a superclass. You can also: Add new properties Add new methods Override the methods of the superclass 18

Calling Superclass Methods You could rewrite the printcircle() method in the Circle class as follows: public void printcircle() { System.out.println("The circle is created " + super.getdatecreated() + " and the radius is " + radius); 19

Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the tostring method defined in GeometricObject */ public String tostring() { return super.tostring() + "\nradius is " + radius; 20

NOTE An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. 21

NOTE Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden. 22

Overriding vs. Overloading public class Test { public static void main(string[] args) { A a = new A(); a.p(10); a.p(10.0); class B { public void p(double i) { System.out.println(i * 2); class A extends B { // This method overrides the method in B public void p(double i) { System.out.println(i); public class Test { public static void main(string[] args) { A a = new A(); a.p(10); a.p(10.0); class B { public void p(double i) { System.out.println(i * 2); class A extends B { // This method overloads the method in B public void p(int i) { System.out.println(i); 23

The Object Class and Its Methods Every class in Java is descended from the java.lang.object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. public class Circle {... Equivalent public class Circle extends Object {... 24

The ArrayList Class You can create an array to store objects. But the array s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects. java.util.arraylist<e> +ArrayList() +add(o: E) : void +add(index: int, o: E) : void +clear(): void +contains(o: Object): boolean +get(index: int) : E +indexof(o: Object) : int +isempty(): boolean +lastindexof(o: Object) : int +remove(o: Object): boolean +size(): int +remove(index: int) : boolean +set(index: int, o: E) : E Creates an empty list. Appends a new element o at the end of this list. Adds a new element o at the specified index in this list. Removes all the elements from this list. Returns true if this list contains the element o. Returns the element from this list at the specified index. Returns the index of the first matching element in this list. Returns true if this list contains no elements. Returns the index of the last matching element in this list. Removes the element o from this list. Returns the number of elements in this list. Removes the element at the specified index. Sets the element at the specified index. 25

Generic Type ArrayList is known as a generic class with a generic type E. You can specify a concrete type to replace E when creating an ArrayList. For example, the following statement creates an ArrayList and assigns its reference to variable cities. This ArrayList object can be used to store strings. ArrayList<String> cities = new ArrayList<String>(); ArrayList<String> cities = new ArrayList<>(); TestArrayList Run 26

Differences and Similarities between Arrays and ArrayList Operation Array ArrayList Creating an array/arraylist String[] a = new String[10] ArrayList<String> list = new ArrayList<>(); Accessing an element a[index] list.get(index); Updating an element a[index] = "London"; list.set(index, "London"); Returning size a.length list.size(); Adding a new element list.add("london"); Inserting a new element list.add(index, "London"); Removing an element list.remove(index); Removing an element list.remove(object); Removing all elements list.clear(); DistinctNumbers Run 27

Array Lists from/to Arrays Creating an ArrayList from an array of objects: String[] array = {"red", "green", "blue"; ArrayList<String> list = new ArrayList<>(Arrays.asList(array)); Creating an array of objects from an ArrayList: String[] array1 = new String[list.size()]; list.toarray(array1); 28

max and min in an Array List String[] array = {"red", "green", "blue"; System.out.pritnln(java.util.Collections.max( new ArrayList<String>(Arrays.asList(array))); String[] array = {"red", "green", "blue"; System.out.pritnln(java.util.Collections.min( new ArrayList<String>(Arrays.asList(array))); 29

Shuffling an Array List Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5; ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array)); java.util.collections.shuffle(list); System.out.println(list); 30

A stack to hold objects. The MyStack Classes MyStack MyStack -list: ArrayList +isempty(): boolean +getsize(): int +peek(): Object +pop(): Object +push(o: Object): void +search(o: Object): int A list to store elements. Returns true if this stack is empty. Returns the number of elements in this stack. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Returns the position of the first element in the stack from the top that matches the specified element. 31

The protected Modifier The protected modifier can be applied on data and methods in a class. A protected data or a protected method in a public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package. private, default, protected, public Visibility increases private, none (if no modifier is used), protected, public 32

Accessibility Summary Modifier on members in a class Accessed from the same class Accessed from the same package Accessed from a subclass Accessed from a different package public protected - default - - private - - - 33

Visibility Modifiers package p1; public class C1 { public int x; protected int y; int z; private int u; protected void m() { public class C2 { C1 o = new C1(); can access o.x; can access o.y; can access o.z; cannot access o.u; can invoke o.m(); package p2; public class C3 extends C1 { can access x; can access y; can access z; cannot access u; public class C4 extends C1 { can access x; can access y; cannot access z; cannot access u; public class C5 { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; cannot access o.u; can invoke m(); can invoke m(); cannot invoke o.m(); 34

A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass. 35

NOTE The modifiers are used on classes and class members (data and methods), except that the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method. 36