Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

Similar documents
Abstract class & Interface

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Object-Oriented Programming in Java

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

Crash Course Review Only. Please use online Jasmit Singh 2

Object Orientated Programming Details COMP360

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Chapter 5. Inheritance

Inheritance. Transitivity

Java Session. Day 2. Reference: Head First Java

Create a Java project named week10

Inheritance and Polymorphism

Object-Oriented Programming More Inheritance

What is Inheritance?

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

PROGRAMMING LANGUAGE 2

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Unit 4 - Inheritance, Packages & Interfaces

Java Object Oriented Design. CSC207 Fall 2014

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS260 Intro to Java & Android 03.Java Language Basics

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

Arrays Classes & Methods, Inheritance

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

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

UNIT - II Object Oriented Programming - Inheritance

Object-Oriented ProgrammingInheritance & Polymorphism

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Programming II (CS300)

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

Inheritance (Part 5) Odds and ends

Lecture 2: Java & Javadoc

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Chapter 1 Introduction to Java

INHERITANCE Mrs. K.M. Sanghavi

Programming overview

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

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

CLASSES AND OBJECTS IN JAVA

Chapter 5 Object-Oriented Programming

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

C++ Important Questions with Answers

Programming II (CS300)

Inheritance. For example, to zoom in on the deer family (cervid), we could make a tree like the following.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

JAVA MOCK TEST JAVA MOCK TEST II

Answer1. Features of Java

Chapter 14 Abstract Classes and Interfaces

ECE 122. Engineering Problem Solving with Java

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

Principles of Object Oriented Programming. Lecture 4

Inheritance (Outsource: )

Data Structures (list, dictionary, tuples, sets, strings)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance & Polymorphism

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Introduction to Programming

Java is an Object Oriented Programming language i.e. it supports four major pillars of OOPS.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Week 5-1: ADT Design

STRUCTURING OF PROGRAM


Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

QUESTIONS FOR AVERAGE BLOOMERS

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Class, Variable, Constructor, Object, Method Questions

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

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Inheritance and Polymorphism

COMP 110/L Lecture 19. Kyle Dewey

ITI Introduction to Computing II

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

CSC207 Week 3. Larry Zhang

CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism

Chapter 2: Java OOP I

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Object-Oriented Programming (OOP) Fundamental Principles of OOP

SRI VIDYA COLLEGE OF ENGG & TECH UNIT -2 INHERITANCE AND INTERFACES SVCET

CMSC 132: Object-Oriented Programming II

1 Shyam sir JAVA Notes

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Inheritance and Encapsulation. Amit Gupta

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Transcription:

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1

In Previous Lecture We learned about OOP which projects the real world in programming language Also we learned about Class: A structure that defines fields and methods Object: An executable copy of a class And each object can encapsulate some fields or methods be referred by or refer to other objects 2

Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). 3

extends Keyword extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. Syntax class Super {...... class Sub extends Super {...... 4

Inheritance Example class Calculation { int z; public void add(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:"+z); public void subtract(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:"+z); public class MyCalculation extends Calculation { public void multiplicate(int x, int y) { z = x * y; System.out.println("The product of the given numbers:"+z); public static void main(string[] args) { int a = 20, b = 10; MyCalculation demo = new MyCalculation(); demo.add(a, b); demo.subtract(a, b); demo.multiplicate(a, b); 5

Example cont d Calculation int z addition() subtraction() MyCalculation int z addition() subtraction() multiplicate() 6

super - Keyword The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used. It is used to differentiate the members of superclass from the members of subclass, if they have same names. It is used to invoke the superclass constructor from subclass. If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below. super.variable super.method(); 7

super - Example class SuperClass { int num = 20; // display method of superclass public void display() { System.out.println("This is the display method of superclass"); public class SubClass extends SuperClass { int num = 10; // display method of subclass public void display() { System.out.println("This is the display method of subclass"); public void mymethod() { this.display(); // Invoking the display() method of sub class super.display(); // Invoking the display() method of superclass // printing the value of variable num of subclass System.out.println("value of the variable named num in sub class:"+ sub.num); // printing the value of variable num of superclass System.out.println("value of the variable named num in super class:"+ super.num); public static void main(string[] args) { SubClass obj = new SubClass(); obj.mymethod(); 8

super - Invoke Constructor If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below. super(values); 9

super - Invoke Constructor class SuperClass { int age; SuperClass(int age) { this.age = age; public void getage() { System.out.println("The value of the variable" + " named age in super class is: " + age); public class SubClass extends SuperClass { SubClass(int age) { super(age); public static void main(string[] args) { SubClass s = new SubClass(24); s.getage(); 10

Type of Inheritance There are various types of inheritance as demonstrated below. 11

Overriding Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super classes or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. 12

Overriding - Example class Animal { public void move() { System.out.println("Animals can move"); class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); public class TestDog { public static void main(string args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class 13

Rules for Method Overriding The argument list and return type should be same with the overridden method. The access level cannot be more restrictive than the overridden method's. If superclass method is declared public, subclass method cannot be either private or protected. A method declared final cannot be overridden. A method declared static is always re-declared. Constructors cannot be overridden. 14

Overriding - Example class Animal { public void move() { System.out.println("Animals can move"); class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); 15

final - Keyword The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: Variable stop value change Method stop method overriding Class stop inheritance 16

final - Example final class FinalClass { final int finalvariable; final public void move() { finalvariable = 2; // ERROR System.out.println( I m final method"); class SubClass extends FinalClass { //ERROR public void move() { //ERROR System.out.println( Method overriding"); public class TestDog { public static void main(string args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class 17

static - Keyword Applies to fields and methods Means that the field/method is defined for the class declaration, is not unique for each instance 18

static - Example Keep track of the number of babies that have been made. public class Baby { int numbabiesmade = 0; Baby() { numbabiesmade += 1; Baby b1 = new Baby(); Baby b2 = new Baby(); System.out.println (b1.numbabiesmade); // 1 System.out.println (b2.numbabiesmade); // 1 System.out.println (Baby.numBabiesMade); // Error! 19

static - Example Keep track of the number of babies that have been made. public class Baby { static int numbabiesmade = 0; Baby() { numbabiesmade += 1; Baby b1 = new Baby(); Baby b2 = new Baby(); System.out.println (b1.numbabiesmade); // 2 System.out.println (b2.numbabiesmade); // 2 System.out.println (Baby.numBabiesMade); // 2 20

Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a super class reference is used to refer to a sub class object. 21

Polymorphism - Instantiate class Animal {... class Lion extends Animal {... class Dog extends Animal {... class Cat extends Animal {... class Wolf extends Animal {... Animal[] animals = new Animal[4]; animals[0] = new Dog(); animals[1] = new Lion(); animals[2] = new Cat(); animals[3] = new Cat(); 22

Polymorphism - Overloading Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different. In the last class we discussed constructor overloading that allows a class to have more than one constructors having different argument lists. Argument lists could differ in 1. Number of parameters. 2. Data type of parameters. 3. Sequence of Data type of parameters. Method overloading is also known as Static Polymorphism. 23

Method Overloading int add (int x, int y) { return x+y; float add (float x, float y) { return x+y; // available codes! 24

Method Overloading int add (int x, int y) { return x+y; float add (float x, float y) { return x+y; int add (int A, int B) {?? int add (int A, int B, float C) {?? int add (float x, int y1, int y2) {?? 25

Method Overloading int add (int x, int y) { return x+y; float add (float x, float y) { return x+y; int add (int A, int B) { ERROR int add (int A, int B, float C) { O int add (float x, int y1, int y2) { O 26

Special Classes ABSTRACT AND INTERFACE 27

Abstraction in PL Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation. *PL: Programming Language 28

Encapsulation Encapsulation, often referred to as "Information Hiding", revolves more specifically around the hiding of the internal data (e.g. state) owned by a class instance, and enforcing access to the internal data in a controlled manner. 29

Abstract Class A class which contains the abstract keyword in its declaration is known as abstract class. Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); ) But, if a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. 30

Abstract Class Assume that the class hierarchy as follow : Animal Mammal Reptile Cat Dog Crocodile I don t want to instantiate Mammal and Reptile! Then, declare those classes using abstract keyword. Mammal[ ] mammallist = new Mammal[5];? 31

Abstract Method If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract. abstract keyword is used to declare the method as abstract. You have to place the abstract keyword before the method name in the method declaration. An abstract method contains a method signature, but no method body. Instead of curly braces, an abstract method will have a semi colon (;) at the end. 32

Abstract Method - Example public abstract class Employee { private String name; private String address; private int number; public abstract double computepay(); // Remainder of class definition Declaring a method as abstract has two consequences The class containing it must be declared as abstract. Any class inheriting the current class must either override the abstract method or declare itself as abstract. 33

Interface An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods (and static/final variables). A class implements an interface, thereby inheriting the abstract methods of the interface. 34

Interface vs Class An interface is similar to a class An interface can contain any number of methods. An interface is written in a file with a.java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a.class file. An interface is different from a class You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract; (do not need use abstract keyword) An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An class can implement multiple interfaces. An interface can extend multiple interfaces. 35

Implements keyword A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); public void travel() { System.out.println("Mammal travels"); public int nooflegs() { return 0; public static void main(string args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); 36

Implementing Multiple Interfaces A Java class can implement multiple interfaces. The implements keyword is used once, and interfaces are declared in a comma-separated list. public class Cat implements Animal, Master 37

Extends keyword An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. // Filename: Sports.java public interface Sports { public void sethometeam(string name); public void setvisitingteam(string name); // Filename: Football.java public interface Football extends Sports { public void hometeamscored(int points); public void visitingteamscored(int points); public void endofquarter(int quarter); // Filename: Hockey.java public interface Hockey extends Sports { public void homegoalscored(); public void visitinggoalscored(); public void endofperiod(int period); public void overtimeperiod(int ot); 38

Extending Multiple Interfaces A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. public interface Hockey extends Sports, Event 39

[Lab Practice #3] To satisfy the requirements, design class hierarchy and implement Animal.java Class Animal // super class Abstract class Mammal extends Animal Fields : int nummammal; Methods : int getnummammals(); Abstract class Reptile extends Animal Fields : int numreptile; Methods : int getnumreptile; Class Cat extends Mammal Fields : String name, float weight, String nameslave; Methods : get/set each fields, meow(), sleep(), breed(); Class Dog extends Mammal Fields : String name, float weight, String namemaster; Methods : get/set each fields, bark(), breed(); Class Crocodile extends Reptile Fields : String name, float weight Methods : get/set each fields, spawn(); 40

[Lab Practice #3] Class Cat, Dog, Crocodile Should be final class Constructor mandatory initiate name and optionally initiate weight Class Cat breed() : breed three kitties // should be implemented meow() : print message (name) : meow sleep() : print message (name) : Zzz Class Dog Breed() : breed five puppies // should be implemented bark() : print message (name) : bowwow Class Crocodile spawn() : spawn twenty eggs 41