Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Programming in Java CSE301 Half Lecture Harry Erwin, PhD University of Sunderland.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Java and C++, The Difference An introduction Unit - 00.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.
Java Implementation: Part 3 Software Construction Lecture 8.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Introduction to Java University of Sunderland CSE301 Harry R. Erwin, PhD.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
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.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
Introduction to Java COM379 (Part-Time) University of Sunderland Harry R Erwin, PhD.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Java Implementation: Part 4 Software Construction Lecture 9.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
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,
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
YG - CS Concept of Encapsulation What is encapsulation? - data and functions/methods are packaged together in the class normally.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
C++ General Characteristics: - Mixed typing system - Constructors and destructors - Elaborate access controls to class entities.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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 and Polymorphism
This pointer, Dynamic memory allocation, Constructors and Destructor
Nested class.
null, true, and false are also reserved.
Extending Classes.
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Chapter 8 Class Inheritance and Interfaces
SPL – PS3 C++ Classes.
Presentation transcript:

Reference Types CSE301 University of Sunderland Harry R Erwin, PhD

Reference Types Summary A ‘reference type’ in Java is an object allocated in main memory (on the heap or free store in other languages). Reference types include objects, arrays, and interfaces. They all inherit from the class Object. (Test Question!) You don’t need to manage memory. That’s handled automagically. Pointers are hidden.

‘Members’ Defined The ‘members’ of a reference type are fields and methods. Members of a reference type can be declared or inherited. Arrays inherit from Object and also have a (constant) length field. Interfaces also inherit from Object.

Classes and Objects A class is a named (or anonymous) collection of fields holding data values and methods. May contain nested inner classes (see Flanagan) Defines a data type ClassName extends the class Object by default. public class ClassName should be stored in a file named ClassName.java Compiles to ClassName.class

The Object Class All reference types inherit from Object. Member methods include: –public boolean equals(Object obj); –public final Class getClass(); // cannot override –public int hashCode(); –public String toString(); // should override! –protected Object clone() throws CloneNotSupportedException; // for deep copying –protected void finalize() throws Throwable; Test Question!

Creating an Object ClassName obj; –Declares that the name obj refers to an obj of class ClassName in the current scope. –Does not create that object. Until the object is created, obj refers to null (e.g., nothing). –To create the object, execute the following: obj = new ClassName(argument list); –Note that the constructor for ClassName may be overloaded. This may result in ‘constructor chaining’. –‘argument list’ is a list of arguments. Test Question!

Other Ways to Create Objects Using literals –String str = “…”; By dynamically loading a class –Class cls = typename.class; typename is the name of a datatype. By copying (cloning) an object Note that the definition of a class happens to be an object in the class Class. Guess where static fields and methods live… 8)

Using an Object or Class To refer to the member fields and methods of an object, use the following syntax: –obj.field; –obj.method(args); To refer to class level (‘static’) fields and methods, use the following syntax: –ClassName.field; –ClassName.method(args);

Access Control ‘public’ class or interface types can be accessed if their package can be accessed. If ‘public’ is not stated for a class or interface, it can only be accessed in the same package (package protected). ‘public’ class members or constructors are accessible. Members of interfaces are implicitly public, while class members are by default package protected. ‘protected’ members are accessible from subclasses or the same package. ‘private’ members are only accessible from the same class. Remind me to diagram this for you. Test Question!

Defining a Class [Modifiers] class ClassName [extends SuperClass] [implements list of Interfaces] { class body } // note no ‘;’! —[] means optional —modifiers may be public, abstract, and/or final. ‘abstract’ means no construction allowed. ‘final’ means no inheritance from it. —SuperClass is the name of the class it inherits from. This defaults to Object if not declared. —The list of interfaces are the interfaces (zero or more) that the class provides methods for.

Class Body Contents Class members include: –Inherited members from the superclass –Inherited members from interfaces –Declared members Private members are not inherited. Constructors and static initializers are not members and are not inherited. Lots of test questions!

Member Fields Modifiers Type Name [= initial value]; –Modifiers include one or more of public, protected, private, final, static, transient, and volatile. –‘static’ means the field is at the class-level. –‘final’ means the field is constant once set. –Initial values are applied either at class initialization if static and otherwise in order of definition. Test Questions!

Member Methods [Modifiers] ResultType Name([arguments]) [throws throwDeclarations] {code} (or ;) –Modifiers: public, protected, private, abstract (special), static (class-level), final (cannot be overriden), synchronized (special), and/or native (special). –ResultType is void or a type. –The list of arguments is similar to that in C. –ThrowDeclarations state the (checked) exceptions the method may throw. –{code} is required in a definition. A terminating ; is used in a declaration. –A name may be used more than once if the argument list is different. This is called overloading. Test Questions

Final Variables If a local variable, member field, or method argument is not supposed to change, declare it final! In C++, this is known as ‘const correctness’. (See Sutter and Alexandrescu, 2005, C++ Coding Standards, Addison-Wesley.) ‘final’ is your friend! Unchanging values are easier to understand, track, and reason about. The compiler checks that an unchanging value is explicitly given only one value in its lifetime.

Static Initializers static {codeBlocks} in the class will be executed at class initialization and can be used to initialize class fields declared prior to the specific static code block being executed. Test Question!

Constructors [Modifiers] ClassName([arguments]) [throws throwDeclarations] {code} –See description of member methods. –Constructor are not members and are not inherited. –The constructor code may begin with: ‘this(argument list);’ to call another constructor of the same class ‘super(argument list);’ to call a constructor of the superclass –That’s called ‘constructor chaining’. –If that does not happen, the code implicitly begins with ‘super();’ –A class with no constructor declarations has an implicit constructor generated for it. –Constructors can be declared private or protected to restrict access. Lots of test questions!

Interfaces May extend other interfaces. An interface lists the member methods that an implementing class must provide. Member fields of an interface are implicitly public, static, and final, and so must be initialized. Test Questions!

Abstract Classes Objects of an abstract class cannot be created in isolation. Hence, to use an abstract class, it must be extended. Member methods of an abstract class may be declared ‘abstract’ with no code. Subclasses must override those methods. Test questions!

Arrays Ordered collection or numbered list of values. All the values are of the same type (although they may be of different subtypes). The type of an array is ClassName[]. Multidimensional arrays are handled as in C or C++. An array can also be declared as follows: –ClassName arrayName[]; // avoid! One way to create: –ClassName[] arrayName = new ClassName[dim]; –Values are initialized to default values for class. The size of an array (the.length field) is constant. Test questions!

Array Literals ClassName[] arrayName = null; –Represents the absence of the object ClassName[] arrayName = {value list}; –Initializes the array entries to the value list. –These must be of type ClassName. Anonymous arrays can also be created: –new ClassName[] {value list} –Frequently used for temporary arguments. Value lists can be multidimensional as in C/C++. Test questions!

Copying and Comparing Reference Types The pointer is copied, not the data. Hence the same data are used. To copy the data (a deep copy), use clone(). If you want to use clone(), you have to override it in your class. Comparisons (e.g., ==) of reference types are done by comparing pointers. Hence two different objects containing the same field values are not equal unless you override equals(). To compare contents, use obj1.equals(Object obj2) You have to override the definition for equals() in your class to compare the fields. First check obj2 is in the correct class (using the ‘instanceof’ operator), then typecast it to an object of that class. Finally compare fields. If you override equals(), you also have to override hashcode(). Important test questions!