2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

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.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
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 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2007.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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.
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.
Cs3180 (Prasad)L8Packages1 Packages Organizing large programs => From monolithic programs to partitioning class name space Access control of names => Enforcing.
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.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Inheritance in the Java programming language J. W. Rider.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
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.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
Nested Classes CompSci 230 S Software Construction.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
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.
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.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Modern Programming Tools And Techniques-I
CompSci 230 S Software Construction
JAVA MULTIPLE CHOICE QUESTION.
Inheritance and Polymorphism
Nested class.
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
null, true, and false are also reserved.
Extending Classes.
Java Programming Language
Advanced Java Topics Chapter 9
Java Inheritance.
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Chapter 5 Classes.
Presentation transcript:

Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and Inner Classes. Interface. Packages in Java. Using multiple classes, packages in Java files.

Jordan Anastasiade. All rights reserved. 2 Creating Classes The fundamental unit of programming in Java is class. public class Sphere { static final double PI = 3.14; double radius; Point3D center; public Sphere(double r, Point3D c) { radius = r; center = c; } double volume() { double v = 4.0/3.0 * PI; return v * radius*radius*radius; } Class Declaration Class Body Constructor Method Fields 1 Modifiers : public,, abstract, final, strictfp 1

Jordan Anastasiade. All rights reserved. 3 Member Variables Member variables declaration appears within the class body but outside of any methods or constructors. public static Vector cubeVertices; private final int id = 0; initilizer 1 Access modifiers: public, protected, private, 2 static – variable is a class variable Attribues final – the value of the variable cannot be changed transient – marker used in object serialization volatile – prevent compiler from optimization typename

Jordan Anastasiade. All rights reserved. 4 Constructors - super(); this(); class AnimationThread extends Thread { int framesPerSecond; int numImages; Image[] images; AnimationThread(int fps) { super("AnimationThread"); super() superclass constructor invocation framesPerSecond = fps; } AnimationThread(int fps, int num) { this(fps); this() explicit constructor invocation numImages = num; } AnimationThread(int fps, int num, Image[] images ) { super("AnimationThread"); framesPerSecond = fps; numImages = num; this.images = images; } this current object reference }

Jordan Anastasiade. All rights reserved. 5 Constructor’s Modifiers One can specify how other objects can create instances of a given class by using an access modifier in the constructors' declaration: private No other class can instantiate the given class. The class may contain public class methods (sometimes called factory methods), and those methods can construct an object and return it, but no other classes can. protected Only subclasses of the given class can create instances of it. public Any class can create an instance of the given class. no modifiers gives package access Only classes within the same package as the class can construct an instance of it.

Jordan Anastasiade. All rights reserved. 6 Method Declaration The only required elements of a method declaration are the method’s name, its return type, and a pair of parentheses ( ). public abstract int doIt(Object o) throws Exception Return type Method nameParametes List Checked exceptions Method Signature 1 Access modifiers: public, protected, private, 2 static – method is a class method abstract – method has no implementation – abstract class final – method cannot be overridden by a subclass native – method implemented in a language other than Java synchronized – method has a thread-safe implementation Attribues strictfp – strict constrain for floating point arithmetic

Jordan Anastasiade. All rights reserved. 7 Overloading Defining more methods with the same name, but with different signature is called method overloading.  Java supports method name overloading so that multiple methods can share the same name. Ex: class ShapeRender { … void draw(Shape s) { …} void draw(Rectagle r) { …} void draw(Circle c, Point position) { …} … }

Jordan Anastasiade. All rights reserved. 8 Inheritance Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all its ancestor. The superclass refers to a direct ancestor. Subclass inherits all superclasses members and can access any member declared as public or protected or declared with no access specifier as long as the subclass is in the same package as the superclasses. public class SubClass extends SuperClass { … } public class SuperClass { … }

Jordan Anastasiade. All rights reserved. 9 Overriding Replacing the superclass’s implementation with a new method in a subclass is called overriding.  The signature and the return type should be identical.  Only accessible non-static method can be overridden.  Access modifier could be different in overridden method as long as the subclass modifier is less restrictive then the superclass.  A subclass can change whether a parameter in an overriddent method is final ( final is not part of method signature).  Each type in overriding method’s throws clause must be polymorphically compatible with a least one of the types listed in the throws clause of the supertype’s method.  Fields cannot be overridden; they can only be hidden. super acts as a reference accessing fields and method of superclass. Ex: super.superclassField;

Jordan Anastasiade. All rights reserved. 10 Example of Overriding class Base { public String str = “BaseString”; public void show() { System.out.println(“Base show() “ + str); } } class Extended extends Base { public String str = “ExtendedString”; public void show() { System.out.println(“Extended show() “ + str); } public static void main(String[ ] args) { Extended e = new Extended(); Base b = e; b.show(); e.show(); System.out.println(b.str + “ “ + e.str); } } Results: 1. b.show()Extended show() ExtendedString 2. e.show()Extended show() ExtendedString 3. b.str + e.strBaseString ExtendedString When invoke a method on an object, the actual class of the object governs which implementation is used. When access a field the declared type of the referenced is used.

Jordan Anastasiade. All rights reserved. 11 Polymorphism class Point { int x; int y; void clear() { x = 0; y = 0 } } class Pixel extends Point { Color color; public void clear() { super.clear(); color = null; } Pixel extends both data and behavior of its Point superclass. All the Point code can be used by any one with a Pixel in hand. A single object like Pixel could have many (poly) forms (-morph) and can be used as both a Pixel object and a Point object. Pixel ’s behavior extends Point ’s behavior. Point point = new Pixel(); Implicit casting – a reference of extended class is assigned to a reference of the base class – upcasting. Point object Pixel

Jordan Anastasiade. All rights reserved. 12 Constructor Order Each constructor has three phases:  1. Invoke a superclass’s constructor.  2. Initialize the fields using their initializers and any initialization block. zero for all numeric types, false for boolean, \u0000 for char, null for references.  3. Execute the body of constructor. Each class has a least one constructor  If class has no constructor the compiler adds the default constructor. Ex: class Bush { Bush(int i){ … } Bush(double d) { …} } An invocation Bush bushObj = new Bush(); will generate a compile error – there is no default constructor.

Jordan Anastasiade. All rights reserved. 13 Abstract Class A method that provides only the definition without an implementation is called abstract method. A class that defines only part of its methods is called and declared as an abstract class. An abstract class could contain abstract mehtods and concret methods Ex: abstract class Benchmark { public long repeat(int count) { long start = System.currentTimeMillis(); for (int k = 0; k < count; k++) long now = System.currentTimeMillis(); benchmark(); return now – start; } abstract void benchmark(); // definition without implementation }

Jordan Anastasiade. All rights reserved. 14 Interface A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface.  Methods in an interface are implicitly abstract and public.  Fields in an interface are always static and final.  A class could implement more than one interface – multiple inheritance.  Interface definition creates type name just as class definition do. Ex: public interface X { int MAX_VAL_SIZE = 10; Object setObject(); } public class A extends B implements X { Object setObject() { Object o; … return o; } }

Jordan Anastasiade. All rights reserved. 15 Interface – a Type Name Interface definitions create type names just as class definition do. An interface defines a protocol of behavior. A class that implements an interface adheres to the protocol defined by that interface. Ex: public interface ConversionFactors { double INCH_TO_MM = 25.4; } public interface Conversions extends ConversionFactors { double inchToMM(double inches); } public class Transform implements Conversions { public double inchToMM(double inches) { return inches * INCH_TO_MM; } Conversions conv = new Transform();

Jordan Anastasiade. All rights reserved. 16 Packages Packages are collections of related classes, interfaces, and subpackages.  Interfaces and class can use normal public names without any conflict with similar common names.  Packages can have types and members that are available only within the package and are inaccessible to outside code. package com.magic.attributes; Ex: Some of the packages in JDK 1.2 java.applet;java.awt;java.awt.*; java.beans;java.io;java.lang; java.rmi;java.security;java.util; java.naming;javax.swing;org.omg.CORBA; Should be the first line in a prgramm

Jordan Anastasiade. All rights reserved. 17 Nested Class Definition: A nested class is a class that is a member of another class. One use nested classes to reflect the relationship between two classes. class EnclosingClass{... class ANestedClass {... } A static nested class is called just that: a static nested class. A nonstatic nested class is called an inner class. class public EnclosingClass {... public static class AStaticNestedClass {... } protected class InnerClass {... }

Jordan Anastasiade. All rights reserved. 18 Inner Class Definition : An inner class is a nested class whose instance exists within an instance of its enclosing class and has direct access to the instance members of its enclosing instance. public class Stack { private Vector items;...//code for Stack's methods and constructors not shown... public Enumeration enumerator() { return new StackEnum(); } class StackEnum implements Enumeration { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); } Instance of Enclosing Class Stack Instance of Inner Class StackEnum

Jordan Anastasiade. All rights reserved. 19 Anonymous Classes Definition : An inner class without a name is called anonymous class. public class Stack { private Vector items;...//code for Stack's methods not shown... public Enumeration enumerator() { return new Enumeration() { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); } Interface Enumeration public boolean hasMoreElements(); public Object nextElement();

Jordan Anastasiade. All rights reserved. 20 Conclusions After completion of this lesson you should know: How to write Java Program using Inheritance. How to write Java Program using Polymorphism. Creating and using Packages.