Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Similar documents
Inheritance in Java. Produced by: Eamonn de Leastar Dr. Siobhán Drohan

Java Overview An introduction to the Java Programming Language

Java Control Statements

The class Object. Lecture CS1122 Summer 2008

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Algorithms. Produced by. Eamonn de Leastar

Introduction to Programming Using Java (98-388)

C12a: The Object Superclass and Selected Methods

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Concepts. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Programming Training for Experienced Programmers (5 Days)

INHERITANCE. Spring 2019

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Java Object Oriented Design. CSC207 Fall 2014

Inheritance. The Java Platform Class Hierarchy

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Inheritance (Part 5) Odds and ends

1 Shyam sir JAVA Notes

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Rules and syntax for inheritance. The boring stuff

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Polymorphism. return a.doublevalue() + b.doublevalue();

CMSC 132: Object-Oriented Programming II

More about inheritance

Core Java Contents. Duration: 25 Hours (1 Month)

Java Fundamentals (II)

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CS-202 Introduction to Object Oriented Programming

Class, Variable, Constructor, Object, Method Questions

c) And last but not least, there are javadoc comments. See Weiss.

Domain-Driven Design Activity

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

5/23/2015. Core Java Syllabus. VikRam ShaRma

CLASS DESIGN. Objectives MODULE 4

Interview Questions I received in 2017 and 2018

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Inheritance. Transitivity

Distributed Systems Recitation 1. Tamim Jabban

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Java Programming with Eclipse

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

WA1278 Introduction to Java Using Eclipse

CS260 Intro to Java & Android 03.Java Language Basics

Index COPYRIGHTED MATERIAL

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output.

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Java 1.8 Programming

Building Java Programs. Inheritance and Polymorphism


COMP 250 Winter 2011 Reading: Java background January 5, 2011

Language Features. 1. The primitive types int, double, and boolean are part of the AP

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Practice for Chapter 11

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Java Magistère BFA

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Abstract Classes and Interfaces

Chapter 10 Classes Continued. Fundamentals of Java

Java Classes, Inheritance, and Interfaces

Java Programming. Price $ (inc GST)

Collections, Maps and Generics

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Annotations in Java (JUnit)

Java: introduction to object-oriented features

Java Training JAVA. Introduction of Java

Brief Summary of Java

CH. 2 OBJECT-ORIENTED PROGRAMMING

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Produced by. Agile Software Development. Eamonn de Leastar

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Java 2 Programmer Exam Cram 2

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Produced by. Agile Software Development. Eamonn de Leastar

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Declarations and Access Control SCJP tips

Objects and Iterators

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

CSCE3193: Programming Paradigms

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

OVERRIDING. 7/11/2015 Budditha Hettige 82

15CS45 : OBJECT ORIENTED CONCEPTS

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CS 231 Data Structures and Algorithms, Fall 2016

Super-Classes and sub-classes

Distributed Systems Recitation 1. Tamim Jabban

Chapter 11: Collections and Maps

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Transcription:

Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

Essential Java Overview Introduction Syntax Basics Arrays Classes Classes Structure Static Members Commonly used Classes Control Statements Control Statement Types If, else, switch For, while, do-while Inheritance Class hierarchies Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interfaces Collections ArrayList HashMap Iterator Vector Enumeration Hashtable Exceptions Exception types Exception Hierarchy Catching exceptions Throwing exceptions Defining exceptions Common exceptions and errors Streams Stream types Character streams Byte streams Filter streams Object Serialization 3

Overview: Road Map Classes in Java What are classes? Defining classes.java files Packages and access level.jar files and classpath Fields, methods, and constructors Static fields and methods Defining and using static fields Defining and using static methods Commonly used classes in Java Object class String and String Buffer classes Class and System classes 3

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 4

Class Modifiers Class Modifiers 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 5

.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 org.tssg.demo.models; public class Policy Policy.java 6

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 org.tssg.pim; 7

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 org.tssg.demo.tests; public class PolicyTester org.tssg.demo.models.policy policy; policy = new org.tssg.demo.models.policy(); 8

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 org.tssg.demo.tests; import org.tssg.models.policy; public class PolicyTester Policy policy; policy = new Policy(); 9

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 10

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 11

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 Policy client premium policynumber 12

Defining Fields A field definition consists of: Access modifier Field type Field name package org.tssg.demo.models; public class Policy private Client client; private String policynumber; private double premium; 13

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 14

Initializing Fields Explicitly Possible when declaring fields Constructors are generally used for initializing fields package org.tssg.demo.models; public class Policy private Client client = new Client(); private String policynumber = "PN123"; private double premium = 1200.00; 15

Field Access Modifier 16

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 17

getters()/setters() To allow access to private fields, getter and setter methods are commonly used Getters return fields values Setters set fields values to passed parameters Policy client premium policynumber getclient getpremium getpolicynumber setclient setpremium setpolicynumber 18

Defining Methods Methods are defined with: Access modifier, same as for fields Return type Method name Parameters, identified with type and name package org.tssg.demo.models; public class Policy public void setclient(client aclient) 19

Constructors Special methods used for creating instances of a class: access modifier same name as the class manipulate new instance package org.tssg.demo.models; public class Policy public Policy() setclient(new Client()); setpolicynumber("pn123"); setpremium(1200.00); 20

Using Constructors Use new before class name to create an instance of a class package org.tssg.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", 1200.00); 21

Policy Class Implementation package org.tssg.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 void setclient(client aclient) this.client = aclient; // other getters and setters.. 22

Overview: Road Map Classes in Java What are classes? Defining classes.java files Packages and access level.jar files and classpath Fields, methods, and constructors Static fields and methods Defining and using static fields Defining and using static methods Commonly used classes in Java Object class String and String Buffer classes Class and System classes 3

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 Often used for constants. 24

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; 25

Accessing Static Fields Static field can be accessed: Directly System.out.println(Count.ONE); 1 Console Indirectly Count count = new Count(); System.out.println(count.INFO); Console Sample Count Class 26

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; 27

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

Overview: Road Map Classes in Java What are classes? Defining classes.java files Packages and access level.jar files and classpath Fields, methods, and constructors Static fields and methods Defining and using static fields Defining and using static methods Commonly used classes in Java Object class String and String Buffer classes Class and System classes 3

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 30

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() 31

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 books are the same if they have the same ISBN. 32

Example equals() method public class Book... public boolean equals(object obj) if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; Book firstbook = new Book("0201914670"); Book secondbook = new Book("0201914670"); if (firstbook.equals(secondbook)) System.out.println("objects are equal"); else System.out.println("objects are not equal"); http://www.java-samples.com/showtutorial.php?tutorialid=660 33

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(); 34

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 35

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 36

Using StringBuffer Class Typical buffer manipulation includes appending, replacing, inserting and deleting characters 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); Console Hello, do you like my hat? Hi, do you like my hat? Hi! 37

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 38

Summary Classes in Java What are classes? Defining classes.java files Packages and access level.jar files and classpath Fields, methods, and constructors Static fields and methods Defining and using static fields Defining and using static methods Singleton pattern Commonly used classes in Java Object class String and String Buffer classes Class and System classes 39

Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License. For more information, please see http://creativecommons.org/licenses/by-nc/3.0/