Object Oriented Programming with Java

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

1 Inheritance Classes and Subclasses Or Extending a Class.
Classes and Objects in Java
8 Copyright © 2005, Oracle. All rights reserved. Object Life Cycle and Inner Classes.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
24-Aug-14 Abstract Classes and Interfaces. Java is “safer” than Python Python is very dynamic—classes and methods can be added, modified, and deleted.
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Abstract Class, Packages and interface from Chapter 9
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
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.
OOP: Inheritance By: Lamiaa Said.
Inheritance Inheritance Reserved word protected Reserved word super
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
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.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 031 Interfaces What is an Interface? Interface Declaration Syntax Implementing Interfaces Using Interfaces as Types Interfaces and Inheritance Interfaces.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Chapter 10 Classes Continued
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
© Amir Kirsh Object Oriented Programming with Java Written by Amir Kirsh.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Inheritance Chapter 10 Programs built from objects/instances of classes An O.O. approach – build on earlier work. Use classes in library and ones you have.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Peyman Dodangeh Sharif University of Technology Fall 2014.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
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…..
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
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,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Chapter 9 Inheritance and Polymorphism
Object Oriented Programming with Java
Java Programming Language
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Java Programming Language
Object Oriented Programming with Java
Presentation transcript:

Object Oriented Programming with Java Written by Amir Kirsh, Edited by Liron Blecher

Agenda All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums

Classes and Objects A class will look like this: <Access-Modifier> class MyClass { // field, constructor, and method declarations } To instantiate an object we will do: MyClass instance = new MyClass(<constructor params>);

Accessibility Options Four accessibility options: – public – (default) = “package” ** – protected * – private * protected is also accessible by package ** called also “package-private” or “package-friendly” Example: public class Person { private String name; protected java.util.Date birthDate; String id; // default accessibility = package public Person() {} }

Static Example: public class Widget { Static member can be accessed without an instance (same as in C++) Example: public class Widget { static private int counter; static public getCounter() {return counter;} } int number = Widget.getCounter(); Called sometimes “class variable” as opposed to “instance variable”

The ‘this’ keyword Example: public class Point { private int x, y; In Java ‘this’ is a reference to myself (in C++ it is a pointer…) Example: public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } The ‘this’ keyword is also used to call another constructor of the same class – we will see that later

Defining constants Example: public class Thingy { Though const is a reserved word in Java it's actually not in use! However the final keyword let's you define constants and const variables Example: public class Thingy { public final static int doodad = 6; // constant public final int id; // constant variable public Thingy(int id) {this.id = id;} // OK //public void set(int id) {this.id = id;} // error! }

Agenda All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums

Constructors Examples in following slides… – Constructors in Java are very similar to C++ – You can overload constructors (like any other method) – A constructor which doesn't get any parameter is called “empty constructor” – You may prefer not to have a constructor at all, in which case it is said that you have by default an “empty constructor” – A constructor can call another constructor of the same class using the ‘this’ keyword – Calling another constructor can be done only as the first instruction of the calling constructor Examples in following slides…

Constructors Example 1: public class Person { String name = ""; // fields can be initialized! Date birthDate; public Person() {} // empty constructor public Person(String name) { this(name, new Date()); //must be in first line } public Person(String name, Date birthDate) { this.name = name; this.birthDate = birthDate;

Constructors Example 2: public class Person { String name = ""; Date birthDate = new Date(); public Person(String name, Date birthDate) { this.name = name; this.birthDate = birthDate; } Person p; // OK p = new Person(); // not good – compilation error

Static Initializer Static initializer is a block of instructions performed the first time a class is loaded Static initializer may be useful to perform a one time initializations of static members Example: public class Thingy { static String s; // the block underneath is a static initializer static { s="Hello"; } } Usually static initializer would do a more complex job…

examples.commandline demo

Agenda All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums

Inheritance Some Terms A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Excepting java.lang.Object, which has no superclass, every class has exactly one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object. A class is said to be descended from all the classes in its inheritance chain stretching back to Object.

Inheritance Examples in following slides… – Class Object is the ancestor base class of all classes in Java – There is no multiple inheritance in Java – Inheritance is always “public” thus type is not stated (no private or protected inheritance as in C++) – Class can implement several interfaces (contracts) – Class can be abstract – Access to base class is done using the super keyword – Constructor may send parameters to its base using the ‘super’ keyword as its first instruction – If the base class does not have an empty constructor then the class is required to pass parameters to its super Examples in following slides…

Inheritance Example 1: public class Person { private String name; public Person(String name) { this.name = name; } // Override toString in class Object public String toString() { return name;

Inheritance Example 1 (cont’): public class Employee extends Person { private Employee manager; public Employee(String name, Employee manager) { super(name); // must be first this.manager = manager; } // Override toString in class Person public String toString() { return super.toString() + (manager!=null? ", reporting to: " + manager : " - I'm the big boss!");

Inheritance Example 2: abstract public class Shape { protected Color line = Color.Black; protected Color fill = Color.White; protected Shape() {} public Shape(Color line, Color fill) { this.line = line; this.fill = fill; } abstract public void draw(); abstract public boolean isPointInside(Point p);

Inheritance Example 2 (cont’): public class Circle extends Shape { private Point center; private double radius; public Circle(Point center, double radius) { this.center = center; this.radius = radius; } public void draw() {…} // use Graphics or Graphics2d public boolean isPointInside(Point p) { return (p.distance(center) < radius);

of course, final and abstract don‘t go together (why?) Inheritance The final keyword is used to forbid a method from being override in derived classes Above is relevant when implementing a generic algorithm in the base class, and it allows the JVM to linkage the calls to the method more efficiently The final keyword can also be used on a class to prevent the class from being subclassed at all Example: abstract public class Shape { … final public void setFillColor(Color color) {<some implementation>} } of course, final and abstract don‘t go together (why?)

examples.inheritance demo

Interfaces Examples in following slides… – Interface is a contract – An interface can contain method signatures (methods without implementation) and static constants – Interface cannot be instantiated, it can only be implemented by classes and extended by other interfaces – Interface that do not include any method signature is called a marker interface – Class can implement several interfaces (contracts) – Class can announce on implementing an interface, without really implementing all of the declared methods, but then the class must be abstract Examples in following slides…

Interfaces Example 1 – using interface Comparable: // a generic max function static public Object max(Comparable... comparables) { int length = comparables.length; if(length == 0) { return null; } Comparable max = comparables[0]; for(int i=1; i<length; i++) { if(max.compareTo(comparables[i]) < 0) { max = comparables[i]; } return max; // calling the function can go like this: String maxStr = (String) max("hello", "world", "!!!");

Interfaces Example 2 – supporting foreach on our own type: To have your own class support iterating, using the "foreach“ syntax, the class should implement the interface Iterable: public interface Iterable<T> { Iterator<T> iterator(); } // example public interface Collection<E> extends Iterable<E> { … Iterator<E> iterator();

Interfaces Example 3 – supporting clone on our own type: To have your own class support the clone method the class should implement the marker interface Cloneable: public interface Cloneable {}

Interfaces Example 4 – new HasName interface: To allow name investigation we want to create a new HasName interface: public interface HasName { String getName(); }

examples.interfaces demo

Agenda All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums

Nested Classes Nested Classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes Non-static nested classes are called inner classes Inner classes that are defined without having their own name are called anonymous classes Examples in following slides…

Nested Classes Example 1: public class OuterClass { private int a; static public class InnerStaticClass { public int b; } public class InnerClass { public void setA(int a1) { a = a1; // we have access to a !!!

Nested Classes Example 1 (cont’): OuterClass.InnerStaticClass obj1 = new OuterClass.InnerStaticClass(); OuterClass.InnerClass obj2 = new OuterClass().new InnerClass(); obj2.setA(3); // we modify a of OuterClass!!!

Nested Classes Example 2 – anonymous class: public interface HaveName { String getName(); } void someFunction(HaveName someoneWithName) { System.out.println(someoneWithName.getName()); public static void main(String[] args) { someFunction(new HaveName() { public String getName() { return "Momo"; } });

examples.innerstaticclass demo

Agenda All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums

Casting Examples in following slides… When you want to convert an object of a superclass to one of its subclasses Use only if you know for sure what the objects’ class type Use instanceof method to check the class type (can also be an interface or any class in the inheritance line) If you fail to check, you might get a ClassCastException Examples in following slides…

Casting Example 1: void foo() { Object obj = new String(“Hiding in an object”); boo (obj); } void boo(Object argument) { if (argument instanceof String) { String myString = (String)argument; System.out.println (myString.toUpperCase());

Agenda All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums

Enums Examples in following slides… Structure for Constant Enumeration Not an integer! - May represent data (= have fields) - May implement methods (member and static) Automatically extends the Enum abstract type Cannot extend other Classes or Enums, but can implement interfaces Cannot be extended (Enums are final) Examples in following slides…

Enums Example 1: public class Card { public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } private final Rank rank; private final Suit suit; private Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } …

Enums Example 1 (cont’): public class Card { … public String toString() { return rank + " of " + suit; } private static final List<Card> deck = new ArrayList<Card>(); // Initialize the static deck static { for (Suit suit : Suit.values()){ for (Rank rank : Rank.values()){ deck.add(new Card(rank, suit))}}; } public static ArrayList<Card> newDeck() { // Return copy of prototype deck return new ArrayList<Card>(deck); } }

Enums Example 2: public enum Operation { PLUS, MINUS, TIMES, DIVIDE; // Do arithmetic op represented by this constant double eval(double x, double y) { switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } throw new AssertionError("Unknown op: " + this);

Enums Example 3: public enum Operation { PLUS { double eval(double x, double y) { return x + y; } }, MINUS { double eval(double x, double y) { return x - y; } }, TIMES { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x, double y); }

examples.enums demo

Links Core Java Interview Questions: http://www.javacodegeeks.com/2013/09/core-java-interview-questions.html