Classes Dwight Deugo Nesa Matic

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
COSC 2006 Data Structures I Instructor: S. Xu URL:
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics 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.
Chapter 10 Classes Continued
Views Dwight Deugo Nesa Matic
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
Workbench Overview Dwight Deugo Nesa Matic
Introduction to Eclipse CSC 216 Lecture 3 Ed Gehringer Using (with permission) slides developed by— Dwight Deugo Nesa Matic
Inheritance Dwight Deugo Nesa Matic
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
10-Nov-15 Java Object Oriented Programming What is it?
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
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™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
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)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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,
Object-Oriented Principals Dwight Deugo Nesa Matic
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.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
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.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
© 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.
 2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Collections Dwight Deugo Nesa Matic
Java IDE Dwight Deugo Nesa Matic
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Sixth Lecture ArrayList Abstract Class and Interface
Introduction to Classes and Objects
Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Programming Language
Object Oriented Programming in java
Java IDE Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chapter 7 Objects and Classes
Presentation transcript:

Classes Dwight Deugo Nesa Matic

2 © , Espirity Inc. Additional Contributors None as of September, 2004

3 © , Espirity Inc. Module Overview 1.Classes in Java 2.Static fields and methods 3.Commonly used classes in Java 4.Searching Java classes in Eclipse

4 © , Espirity Inc. Module Road Map 1.Classes in Java  What are classes?  Defining classes .java files  Packages and access level .jar files and classpath  Fields, methods, and constructors 2.Static fields and methods 3.Commonly used classes in Java 4.Searching Java classes in Eclipse

5 © , Espirity Inc. What is a Class? A class defines an object by defining its state and behavior A class is also collection of objects that encapsulate similar data and behavior Classes are used for creating new objects Classes define objects type

6 © , Espirity Inc. How to Define Java Class? Java class is defined with using class keyword  Class name follows the keyword, and by convention starts with capital letter  For example Policy, Client, House, etc. Class access level must be specified before the class keyword public class Policy{ … }

7 © , Espirity Inc. Class Modifiers Class Modifies identifies visibility of the class There are two access modifiers for a class:  public  Identifies that any other class can reference defined class  Not specified  Identifies that only classes defined in the same package can reference defined class  It is default access level modifier

8 © , Espirity Inc..java Files Java classes are contained in.java files  One file can contain one public class  One file can contain more than one non-public classes The file name is the same as the class name contained in the file package com.espirity.demo.models; public class Policy{ … } Policy.java

9 © , Espirity Inc. Package Package groups related classes  Classes are usually related by their functionality, for example domain classes, testing classes, etc. Package is identified using package keyword Package is unique identifier for a class  Two classes with a same name cannot be in the same package  Different packages can contain same class names package com.espirity.demo.models;

10 © , Espirity Inc. Referencing Classes A class must be fully referenced every time when used outside of its package Full qualifier for a class is used  package name + class name package com.espirity.demo.tests; public class PolicyTester{ com.espirity.demo.models.Policy policy; … policy = new com.espirity.demo.models.Policy(); }

11 © , Espirity Inc. Import Statement Used to identify which classes can be referenced without fully identifying them  Specified with import keyword  Can specify a class, or all classes from a package package com.espirity.demo.tests; import com.espirity.demo.models.Policy; public class PolicyTester{ Policy policy; … policy = new Policy(); }

12 © , Espirity Inc. Ambiguities in Importing Classes Happens when same class is imported from different packages Compiling error states that there is ambiguity is using the class  Explicit reference to the class must be made package com.espirity.demo.tests; import com.espirity.demo.models.*; import com.insurancecompany.policyapp.models.*; public class PolicyTester{ Policy policy; … policy = new Policy(); } Ambiguity in type Policy

13 © , Espirity Inc. Compiling Classes When writing Java class, the source code is stored in.java files When compiling Java classes, compiled code is stored in.class files Compiled Java classes from the same package are compiled into the same directory  The directory name matched package name

14 © , Espirity Inc. Classpath and.jar files Classpath allows Java Virtual Machine to find the code  CLASSPATH environment variable is used to indicate the root of where packages are  Packages are subdirectories under the root Compiled Java classes can be packaged and distributed in Java Archive (.jar) files  Packages in the.jar file are replaced with directories

15 © , Espirity Inc. What are Fields? Object state is implemented through fields Fields are defined at the class level  All instances of the same class have the same fields  Fields values can be different from instance to instance Fields are also knows as instance variables Policy client premium policyNumber

16 © , Espirity Inc. Defining Fields A field definition consists of:  Access modifier  Field type  Field name package com.espirity.demo.models; public class Policy { private Client client; private String policyNumber; private double premium; }

17 © , Espirity Inc. Initializing Fields Fields are initialized when new instance of a class is created Primitive type fields get a default value  Numeric primitives are initialized to 0 or 0.0  boolean primitives are initialized to false  Reference type fields are initialized to null as they do not yet reference any object Fields can also be explicitly initialized when declared

18 © , Espirity Inc. Initializing Fields Explicitly Possible when declaring fields Not commonly used  Constructors are generally used for initializing fields package com.espirity.demo.models; public class Policy { private Client client = new Client(); private String policyNumber = "PN123"; private double premium = ; }

19 © , Espirity Inc. Field Access Modifier There are four different modifiers:  public  Allows direct access to fields from outside the package where class is defined  protected  Allows direct access to fields from within the package where class is defined  default  Allows direct access to fields from within the package where class is defined and all subclasses of the class  private  Allows direct access to fields from class only

20 © , Espirity Inc. What are Methods? Methods represent behavior of an object  All instances of the same class have same methods defined and understand same messages When a message is sent to an object, method that corresponds to that message is executed  Methods represent implementation of messages

21 © , Espirity Inc. Methods and Encapsulation To allow access to private fields, getter and setter methods are commonly used  Getters return fields values  Setters set fields values to passed parameters Getters and setters enforce encapsulation Policy client premium policyNumber getClient getPremium getPolicyNumber setClient setPremium setPolicyNumber

22 © , Espirity Inc. Defining Methods Methods are defined with:  Access modifier, same as for fields  Return type  Method name  Parameters, identified with type and name package com.espirity.demo.models; public class Policy { … public void setClient(Client aClient){ … }

23 © , Espirity Inc. Constructors Special methods used for creating instances of a class:  access modifier  same name as the class  manipulate new instance package com.espirity.demo.models; public class Policy { … public Policy(){ setClient(new Client()); setPolicyNumber("PN123"); setPremium( ); }

24 © , Espirity Inc. Using Constructors Use new before class name to create an instance of a class package com.espirity.demo.models; public class Policy { … public Policy(Client aClient, String policyNumber, double premium){ setClient(aClient); setPolicyNumber(policyNumber); setPremium(premium); } Policy policy = new Policy(new Client(), "PN123", );

25 © , Espirity Inc. Policy Class Implementation package com.espirity.demo.models; public class Policy { private Client client; private String policyNumber; private double premium; public Policy(Client aClient, String policyNumber, double premium){ setClient(aClient); setPolicyNumber(policyNumber); setPremium(premium); } public Client getClient() { return client; } public String getPolicyNumber() { return policyNumber; } public double getPremium() { return premium; } public void setClient(Client aClient) { this.client = aClient; } public void setPolicyNumber(String policyNumber) { policyNumber = policyNumber; } public void setPremium(double premium) { premium = premium; }

26 © , Espirity Inc. Module Road Map 1.Classes in Java 2.Static fields and methods  Defining and using static fields  Defining and using static methods  Singleton pattern 3.Commonly used classes in Java 4.Searching Java classes in Eclipse

27 © , Espirity Inc. What are Static Fields? Static fields represent data shared across all instances of a class  There is only one copy of the field for the class  Modification to the static field affects all instances of the class Static fields are also knows as class variables Some of the static fields usages include:  Constants  Implementation of singleton pattern

28 © , Espirity Inc. Declaring Static Fields Declared by using the static keyword Java constants are declared as static final fields  Modifier final indicates that field value cannot be changed public class Count{ public static String INFO = "Sample Count Class"; public final static int ONE = 1; public final static int TWO = 2; public final static int THREE = 3; }

29 © , Espirity Inc. Accessing Static Fields Static field can be accessed:  Directly  Indirectly  Cannot access final fields directly System.out.println(Count.ONE); Count count = new Count(); System.out.println(count.INFO); 1 Console Sample Count Class Console

30 © , Espirity Inc. Static Methods Define behavior related to the class, not individual instances  Defined by using the static keyword  Commonly used for accessing static fields  Getter and setter methods public class Count{ private static String INFO = "Sample Count Class"; public final static int ONE = 1; public final static int TWO = 2; public final static int THREE = 3; public static String getInfo(){ return INFO; }

31 © , Espirity Inc. Using Static Methods Static methods can be also accessed by instance or class Count count = new Count(); System.out.println(count.getInfo()); Sample Count Class Console System.out.println(Count.getInfo()); Sample Count Class Console

32 © , Espirity Inc. Singleton Pattern Ensures existence of only one instance of a class  This instance is usually stored in the static field and accessed through a static method public class Singleton { private static Singleton theInstance; public static Singleton getInstance(){ if (theInstance == null){ theInstance = new Singleton(); } return theInstance; } private Singleton(){ super(); }

33 © , Espirity Inc. Using Singleton Pattern Call on creation of new instance will fail Calling the static method will return the instance new Singleton() The constructor Singleton() is not visible error Singleton.getInstance() Returns only instance of the class

34 © , Espirity Inc. Module Road Map 1.Classes in Java 2.Static fields and methods 3.Commonly used classes in Java  Object class  String and String Buffer classes  Class and System classes 4.Searching Java classes in Eclipse

35 © , Espirity Inc. Package java.lang It is a core package in Java When classes from this package are referenced there is no need for import statement Contains core set of classes such as:  Object  String  StringBuffer  System  Class

36 © , Espirity Inc. Object Class Object class is the top of the class hierarchy in Java  Every class inherits from Object class  Defines some default behavior that is mainly overridden in subclasses Commonly overridden methods from Object class are:  toString()  equals()  hashCode()  clone()

37 © , Espirity Inc. Method equals() Meant to return whether or not two objects are equal  Default implementation in Object class returns whether or not are objects identical  The == operator is used  Overriding method allows to change the equality criteria  For example two policies are the same if they have the same client, same policyNumber and same premium

38 © , Espirity Inc. Example equals() method An example of overriding the equals() method in the Policy class  Two policies are equal if their policy numbers are equal public boolean equals(Object anObject){ if ((anObject == null)||(anObject.getClass() != this.getClass())) return false; Policy policy = (Policy)anObject; return getPolicyNumber().equals(policy.getPolicyNumber()); }

39 © , Espirity Inc. Method hashCode() Used by collections, primarily HashMap and HashSet  Returns an int for indexing  Hash codes must be identical for objects that are equal  For the Policy class implementation of the hash code method could be: public int hashCode(){ return getPolicyNumber().hashCode(); }

40 © , Espirity Inc. Method clone() Used to obtain copy of an object The default implementation of the clone() method in Object class does shallow copy  New instance of the class is created, but all containing fields are the same Policy policy; policy = new Policy(); Policy policyCopy; policyCopy = policy.clone(); policy policyCopy client policy Number premium

41 © , Espirity Inc. Cloning Rules Classes must implement Cloneable interface to allow their instances to be cloned  CloneNotSupported exception thrown if objects cannot be cloned  In our example, both Client and Policy classes must implement Cloneable interface to support cloning Method clone() is protected in Object class  Usually made public when overridden to allow use everywhere

42 © , Espirity Inc. String Class Used for manipulating constant set of characters Literals are String instances that cannot be changed, and have fixed size String greeting = "Hello" + ", do you like my hat?"; //"Hello, do you like my hat?" String hello = greeting.substring(0,5); //"Hello" String upercase = hello.toUpperCase(); //"HELLO THERE!" boolean isEqual = hello.equals("HELLO"); //false boolean isEqual1 = hello.equalsIgnoreCase("HELLO"); //true

43 © , Espirity Inc. StringBuffer Class Used for strings that can change Allows for adding, replacing and deleting characters  When characters are added size increases  StringBuffer object knows about its length and capacity  length indicates how many characters it has  capacity indicates how many characters it can currently hold

44 © , Espirity Inc. Using StringBuffer Class StringBuffer buffer = new StringBuffer(); buffer.append("Hello"); buffer.append(", do you"); buffer.insert(13, " like my hat?"); System.out.println(buffer); buffer.replace(0,5,"Hi"); System.out.println(buffer); buffer.delete(2,buffer.length()-1); buffer.replace(buffer.length()-1, buffer.length(), "!"); System.out.println(buffer); Hello, do you like my hat? Console Hi, do you like my hat? Typical buffer manipulation includes appending, replacing, inserting and deleting characters Hi!

45 © , Espirity Inc. Class Java classes are not objects themselves  They are templates for data and behavior and also factory for creating instances Instances of Class class represent Java classes runtime  They allow developers to find runtime information about the class

46 © , Espirity Inc. Class Protocol Allows for queering the class  Finding methods, fields and more HomePolicy policy = new HomePolicy(1200); Class policyClass = policy.getClass(); //class HomePolicy policyClass.getDeclaredFields(); //[private House HomePolicy.house] Class policySuperclass = policyClass.getSuperclass(); //class Policy policySuperclass.getName(); //Policy

47 © , Espirity Inc. System Class Provides an access to system functions through its static protocols  It is not possible to create instances of System class  Defines static methods and fields System.out.println("Hello, do you like my hat?"); Hello, do you like my hat? Console

48 © , Espirity Inc. Module Road Map 1.Classes in Java 2.Static fields and methods 3.Commonly used classes in Java 4.Searching Java classes in Eclipse  Search use  Search view  Result view

49 © , Espirity Inc. Searching in Eclipse It is impossible to know entire Java library  Eclipse helps with its extensive built-in search mechanism It allows for searching on:  Classes  Methods  Constructor  Field  Package It allows searching for:  Declarations  References

50 © , Espirity Inc. Search View Opens by choosing Search from the pull-down menu

51 © , Espirity Inc. Search Result View Contains results of performed search Double-click on the item in the result view opens requested Java type

52 © , Espirity Inc. Review In this module we discussed:  Java classes, packages, fields and methods  Access level  Static fields, and methods  Singleton pattern  Commonly used classes in Java  Searching for Java classes in Eclipse