Java and OOP Part 5 – More.

Slides:



Advertisements
Similar presentations
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Advertisements

George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Intro to OOP with Java, C. Thomas Wu
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Introduction to Exceptions in Java CS201, SW Development Methods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Chapter 7: Cloning and RTTI
JAVA MULTIPLE CHOICE QUESTION.
Data Structures and Algorithms revision
MIT AITI 2003 Lecture14 Exceptions
Inheritance and Polymorphism
Lecture 5: Some more Java!
Java Programming Language
CSE 413, Autumn 2002 Programming Languages
Inheritance in Java.
CIS3023: Programming Fundamentals for CIS Majors II
Templates.
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
What/how do we care about a program?
Advanced Programming Behnam Hatami Fall 2017.
Chapter 9 Inheritance and Polymorphism
null, true, and false are also reserved.
Interface.
Extending Classes.
Java Programming Language
Web Design & Development Lecture 7
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
CMSC 202 Generics.
Interfaces.
Java Programming Language
Exceptions 25-Apr-19.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Review of Previous Lesson
Chapter 12 Exception Handling and Text IO Part 1
Creating and Modifying Text part 3
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Tutorial MutliThreading.
Exceptions 10-May-19.
Why do we need exceptions?
Chapter 11 Inheritance and Encapsulation and Polymorphism
Exceptions 5-Jul-19.
Exception Handling.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Java and OOP Part 5 – More

More OOP More OOP concepts beyond the introduction: constants this clone and equals inheritance exceptions reflection interfaces

Constants final is used for classes which cannot be sub-classed Data members can also be declared final Which means they are constants – for example public final double π = 3.1415926; Also note you can use Unicode in source code

field1 of the object carrying out someMethod this Keyword this is a reference to the object executing the current method Usually this can be omitted public void someMethod() { field1=99; field2=32; } field1 of the object carrying out someMethod We could have said this.field1=99;

Example of this public void putInQueue() { q.add(this); } This might be a method to place an object in a queue. The queue has a method add, and we need to pass to it a reference to the object to be added to the queue

Exercise Set up code to do the last example. Follow these steps - Define a Queue class. This holds objects in an array. Have 3 data members - the current size (how many objects currently in the array), a max size, and the array itself. Have a constructor which takes as argument the max size required. Have an add method which adds an object to the array, and a display method Define a QueueableObject class. It has just one data member - which Queue object it will be stored in. It has just one method - putInQueue In main(), make 1 Queue. Then make some Queueable objects, add them to the queue, and display the queue.

object = object? Two distinct questions - are 2 objects the same? (Do 2 references refer to th esame object) do 2 objects contain equal data?

Example .equals Integer i1 = new Integer(4); if (i1.equals(i2)) YES System.out.println("Contain same data"); if (i1 == i2) NO System.out.println("Same object");

Example = Integer i1 = new Integer(4); Integer i2=i1; if (i1.equals(i2)) YES System.out.println("Contain same data"); if (i1 == i2) YES System.out.println("Same object");

Over-riding clone public class CloneableClass { public CloneableClass(int i) { field1=i; } public CloneableClass clone() { CloneableClass newOne = new CloneableClass(field1); return newOne; private int field1; CloneableClass c1 = new CloneableClass(9); CloneableClass c2 = c1.clone();

Danger - why is this wrong? public class CloneableClass { public CloneableClass clone() { CloneableClass newOne = new CloneableClass(); newOne.field1=this.field1; return newOne; } public int[] field1 = {1,2,3};

Because.. CloneableClass c1 = new CloneableClass(); CloneableClass c2 = c1.clone(); c1.field1[1]=99; System.out.println(c2.field1[1]); // outputs 99 c1 object c2 object same array - we didn't make a new one the field1 array

Exercise Copy the CloneableClass and fix its clone method

Exceptions exception = unusual situation here program cannot execute 'normally' with a more-or-less external cause not a program bug eg file not found connection with server lost out of memory broken Java machine

Exceptions Some methods are declared to 'throw' an exception Compiler will insist code 'catches' checked exception Code form - try { .. call of method that may throw ExceptionType } catch ( ExceptionType e) { .. code to deal with exception

Example try catch FileReader fr = null; try { fr= new FileReader("test.dat"); } catch (FileNotFoundException fe) { System.out.println("Cant find file"); FileReader is in package java.io Note declare fr outside try and initialise Else compiler complains fr may not be initialised

Exercise A FileReader inherits a method called read read takes a char[] as argument Look at the documentation Extend the code on the last slide to display the file

More on inheritance Suppose we have a base class called BaseClass, and that SubClass extends this. What do we get if we say: BaseClass s = new SubClass();

More on inheritance Suppose we have a base class called BaseClass, and that SubClass extends this. What do we get if we say: BaseClass s = new SubClass(); Then s is an object which is 'really' a SubClass But its been declared to be a BaseClass What happens? We get the subclass methods, but The base class fields For example

Example public class BaseClass { public void method() { System.out.println("Base class method"); } public int field=1;} public class SubClass extends BaseClass { public void method() System.out.println("Subclass method"); } public int field = 2; BaseClass s = new SubClass(); s.method(); System.out.println(s.field); outputs: Subclass method 1

Reflection Sometimes your code must deal with objects when you do not know what type they are Reflection enables you to ask an object what class it is A Class object carries info about a class The Object class has a method called getClass So all classes have this - eg BaseClass s = new SubClass(); Class theClass= s.getClass(); System.out.println(theClass); .. outputs class test.SubClass (SubClass was defined in package test)

This example shows how we can trace up a class hierarchy See the doc of Class for more info public static void main(String[] args) { BaseClass s = new SubClass(); Class theClass= s.getClass(); upTree(theClass); } public static void upTree(Class someClass) { if (someClass==null) return; System.out.println(someClass); upTree(someClass.getSuperclass()); output: class test.SubClass class test.BaseClass class java.lang.Object Using Class objects

Reflection exercise Look at the doc of Class Use Class.forName and .getMethods to output the methods of a given class Note .forName needs package eg theClass= Class.forName("java.lang.Class"); and need to catch exception

No multiple inheritance In some languages (C++) a class can inherit from more than one super class Called multiple inheritance Cannot do it in Java Idea of interface kind of substitute Enables a class to 'be like' more than one class interface Interfaces heavily used in Swing - simpler than what follows..

What is an interface Like a ghostly class An interface has a set of methods (names, arguments, return types) The interface declares but does not define the methods A class can be declared to implement the interface It must then define the methods in the interface Or the compiler will complain Classes can implement several interfaces

Example interface Comparable just one method - int compareTo(Object obj) should return negative, 0 or positive depending on whether obj comes before, is =, or comes after

Example implementation public class Order implements Comparable { public Order(double amount, int id, int day, int month, int year) value=amount; key = id; date=new GregorianCalendar(); date.set(year, month, day); } public int compareTo(Object obj) Order otherOne = (Order) obj; return date.compareTo(otherOne.date); private GregorianCalendar date; private double value; private int key; Calendar implements Comparable

Using a Comparable class Order order1 = new Order(34.50, 1, 2, 1, 2004); Order order2 = new Order(44.50, 2, 1, 1, 2004); System.out.println(order1.compareTo(order2)); get 1 Exercise Copy the Order class Change it so it compares on order value not order date Test it

Variables of interface type You can declare variables of a type which is interface not a class eg Comparable someObj; But you can't refer to any method other than that in the interface Enables you to write routines which work on any object which implements the interface So you could write a Sorter class which would sort arrays of any Comparable type (like a template in C++):

Example : the Sorter class public class Sorter { public static void sort(Comparable[] things) { .. .. the sort method.. } in use.. String[] array = {"ppp", "a", "aaa", "ccc"}; Sorter.sort(array); for (int i = 0; i<array.length; i++) System.out.println(array[i]); output - a aaa ccc ppp

Exercise Copy the Sorter class Fill in the sort method eg a bubble sort Check it works Check it works with arrays of other Comparable types eg Integer