Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism = slide covered in class – others for reference.

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Chapter 4 Objects and Classes.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Topic 4 Inheritance.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
BY:- TOPS Technologies
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
03/10/14 Chapter 9 Inheritance.
OOP’S Concepts in C#.Net
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Inheritance Inheritance is a fundamental Object Oriented concept
Java Inheritance.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism = slide covered in class – others for reference

Sample class… public class Bicycle { public int cadence; public int gear; public int speed; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } What is the class name? What are the attributes? (fields)? What does the class “do”? Methods? Pick out all the java language words e.g. public is a reserved java word.. Notice.. indentation Brackets { } Java words Case conventions..

public class Bicycle { public int cadence; public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } // the Bicycle class has four methods public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } Comments in your code // ALWAYS comment your code // each method // each attribute.. Comments

Class vs Instance Objects Class members –class fields –class methods Instance members –instance fields –instance methods

Class Members Class members (fields and methods) are associated with the class in which they are defined –exist only once, a single copy –declared using the static keyword –class members are accessed using the class name ClassName.classMemberName

Class fields and Methods Class fields –a class field has the same value for all instances of the object –a class field declared with a final modifier is a constant static final double PI= ; Why would you do this? Class methods –a class method cannot use any instance members (fields or methods) –Used for a method that is same for all objects

Class method class MyUtils { public static double mean(int[] p) { int sum = 0; // sum of all the elements for (int i=0; i<p.length; i++) { sum += p[i]; } return ((double)sum) / p.length; }//endmethod mean } // Called from outside the MyUtils class – uses Class name double avgAtt = MyUtils.mean(attendance);

Instance members Instance members are associated with instances of the class –exist for each separate instance –copied as the object is instantiated –instance fields in different instance objects can have different values

Example – class vs instance public class BankAccount{ // instance fields String name; double balance; // class field static double interestRate; // instance method public double getBalance(){ return balance; } // class method public static double getRate(){ return interestRate; }... }

Example – class vs instance Code to setup and use BankAccounts //instantiate a BankAccount BankAccount myAcc = new BankAccount(...); // access its instance field balance System.out.println(myAcc.getBalance()); // access its class field interestRate System.out.println(BankAccount.interestRate); default constructor Class name

Method Overloading Defining methods within the same class with the same name but with different parameter lists Java compiler determines which method to call based on the parameter list Often used for constructors BankAccount(String name){ this.name=name; this.balance=0; } BankAccount(String name, double balance){ this.name=name; this.balance=balance; };

Inheritance Inheritance allows classes to be considered in a hierarchy with the data and methods of the parent (super) class being passed onto (inherited) by the child (sub) classes and not needed in their specifications implemented using the extends keyword e.g. class subClass extends superClass { … } an instance of subClass can also be treated as an instance of the superClass Examples?

Object class Every class defined has a superclass If a superclass is not explicitly defined it is the superclass java.lang.Object Object is a special class –the only class that does not have a superclass –all Java classes inherit the methods of Object –instances of any class can be treated as an instance of Object –all arrays are also considered instances of Object

Inheritance example public class LoanAccount extends BankAccount{ double loanAmount; int loanPeriod;// no of yrs... } Bank account had name and balance LoanAccount has extra fields specific to Loan accounts

Super Constructors are not inherited by subclasses A subclass should call the constructor of its superclass to perform the initialisation on the instance fields that the superclass is responsible for This is done using the super reference super(param1, param2,…) must always be the first line in the subclass constructor code

super Example public class BankAccount{ String name; double balance=0; public BankAccount (String name){ this.name=name; }... } public class LoanAccount extends BankAccount{ double loanAmount; int loanPeriod;// no of yrs public LoanAccount(name, amt, period){ super(name); this.loanAmount=amt; this.loanPeriod=period; }... }

Points about Inheritance Multiple Inheritance –a Java class may only extend from one superclass - multiple inheritance is not supported (see interfaces for work around) A class that is declared with the final modifier cannot be extended or subclassed This allows control over a class, so that no one can subclass the class and possibly introduce anomalous behavior. E.g. Java.lang. String class

public final class MyFinalClass {.. } public class NotAllowed extends MyFinalClass {...} // forbidden Points about Inheritance

Working within a hierarchy –any object of a subclass can be assigned to an object of a superclass –any object of a superclass can be assigned to an object of a subclass with an appropriate cast BankAccount myAcc = new BankAccount(…); //superclass LoanAccount myLoan = new LoanAccount(…); //subclass myAcc = myLoan; // OK assign subclass to superclass myLoan = myAcc // not OK why not? myLoan = (LoanAccount) myAcc; // OK if(myAcc instanceOf LoanAccount) LoanAccount myLoan = (LoanAccount) myAcc; // better

Overriding Methods Overriding is where a subclass decides to supply its own version of an instance method already supplied by its superclass –general or default method provided in superclass –more specialised method provided in subclass –Any examples?

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. This method overrides the animal Move method } The benefit of overriding is: ability to define a behavior that's specific to the sub class type. In OO terms, overriding means to override the functionality of any existing method.

toString() Example - toString() method - The root Object class has a toString() method which allows an object of the class to be output as a string public String toString(); The toString() method is overridden at all levels in the hierarchy so that you can write out details of an object in whatever suits your object Useful for outputing details of any object System.out.println(“Account details: “+myAcc); string concatenation automatically invokes a toString() on myAcc to convert it to a String

Overriding example public class BankAccount { public String toString(){ String s=“Bank Account for ”; s+=name+”\nbalance= “+balance; return s; } } public class LoanAccount extends BankAccount{ public String toString(){ String s=“\nLoan Account for ”; s+=name+”\nbalance= “+balance; s+=“Loan of ”+loanAmt; s+=“ for ”+loanPeriod+ “years”; return s; } } What happens if you don’t override the toString() method?

super use the super keyword to invoke the superclass version of an overridden method // Bank Account toString method public String toString(){ String s=“Account for ”; s+=name+”\nbalance= “+balance; return s; } // Loan Account toString method public String toString(){ String s= super.toString(); s+=“Loan of ”+loanAmt; s+=“ for ”+loanPeriod+ “years”; return s; }

Overriding Where there are several instances of the same method in a hierarchy – the one in the closest subclass is always used. Even if an object of the subclass is assigned to an object of the superclass and method is invoked from the subclass. System.out.println(myAcc); uses BankAccount toString() System.out.println(myLoan); uses LoanAccount toString() myAcc=myLoan; System.out.println(myAcc); still uses LoanAccount toString()

Dynamic Binding Overriding uses dynamic binding or dynamic method lookup to find the correct method at run time. Dynamic binding is also known as virtual method invocation Note: Overriding is not the same as Overloading Overloading does not use dynamic binding (because overloading is understood at compile time.)

Dynamic Binding Animal myAnimal = new Dog(); The variable on the left is type Animal, but the object on the right is type Dog. If the Dog class has a method that is the same as a method in the Animal class, then the version of the method in the Dog class will be called. For instance, if both classes define a method called show(), and you do this: myAnimal.show(); the version of show() in the Dog class will be called. The type of the object that is assigned to the Animal variable determines the method that is called. When the compiler scans the program and sees that statement it knows that myAnimal is of type Animal, but the compiler also knows that myAnimal can be a reference to any class derived from Animal. Therefore, the compiler doesn't know what version of show() that statement is calling. It's not until the assignment: Animal myAnimal = new Dog(); is executed at runtime that the version of show() is determined: = dynamic binding

Polymorphism Overriding + dynamic binding = polymorphism Polymorphism “literally: different forms”.. –is the ability of different objects to respond to the same message (method) in their own way Need examples to understand this…

Polymorphism example abstract class Account { int balance; abstract void withdraw(int amount); } class LoanAccount extends Account { void withdraw(int amount) { /* Some sort of calculation specific to withdrawaing from a loan account.. */ } } class FixedAccount extends Account { void withdraw(int amount) { /* a calcalculation specific to withdrawing from a fixed accounts */ } An account class, With two subclasses – fixed account, loan account – both of which withdraw money in their own way

Polymorphism example //In some other piece of code.. An object called “MyAcct”.. wants to Withdraw 40 euro...// MyAcct.withdraw(40); How it withdraws money will be decided at run time when the system examines its object type..fixedAccount versus LoanAcct..This is polymorphism. Why is this important? What coding efficiency do you gain from this? Supposing the behaviour of withdrawing money from a locan account changed..Or you added a new type of account..

Encapsulation Encapsulation is the packaging of the object’s fields (and internal methods) within a protective shell/capsule of its methods –an object has a “public” interface that other objects use to communicate with it –an object maintains “private” information that can be changed without affecting other objects that depend on it or use it –“blackbox” effect Encapsulation achieved using Information Hiding. Think “coffee machine”…

Encapsulation To implement encapsulation –All fields should be private –Include ‘get’ and ‘set’ methods (accessor methods) for all fields that need to be accessed by users –Hide internal methods (i.e. methods that are not relevant to users but are only used by the class itself).

Information Hiding Information Hiding – reveal only what is needed to the user of the object –hides implementation details from user –facilitates maintenance –protects against willful or accidental damage –keeps API simple and “uncluttered” –facilitates ease of understanding and use

Accessibility Modifiers Information Hiding implemented through accessibility modifiers –public = accessible to any other object –private = accessible within the object itself –protected = accessible within the object and any of its subclasses (and to all classes within the package)

Java Packages & Classpath

Packages A Package is a group of classes available for download and use Java’s way of organising classes in different groups..

Packages To use a package (other than java.lang) it must be imported into your Java program import myPackage.*; // (saw this with java.io.*;) will make all classes in package myPackage accessible to your class import myPackage.class1; will make class1 in package myPackage accessible to your class. packages are imported at the top of the source code before any class definitions Eclipse takes care of this mostly…

Java packages Java Packages available with the JDK –java.io – for system input and output –java.math – for integer and decimal arithmetic –java.text - for handling text, dates, numbers… –java.util – for collections, date & time facilities... –java.net – for implementing networking apps –java.sql – for accessing data in a data source –and many more…

Creating a Package Groups of classes which are related can be placed in a package Each source file that is to be part of the package must include package packageName; at the start of the source code The class files for the package must be placed in a directory with the same name as the package Eclipse takes care of this mostly…