Dennis Olsson. Tuesday 31 July



Similar documents
Classes Dennis Olsson

CS 111 Classes I 1. Software Organization View to this point:

Java CPD (I) Frans Coenen Department of Computer Science

Fundamentals of Java Programming

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Java Interview Questions and Answers

Chapter 1 Java Program Design and Development

Java Application Developer Certificate Program Competencies

C++ INTERVIEW QUESTIONS

Course MS10975A Introduction to Programming. Length: 5 Days

Software Construction

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Java Programming Language

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter 1 Fundamentals of Java Programming

CS506 Web Design and Development Solved Online Quiz No. 01

Course Title: Software Development

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

Crash Course in Java

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

No no-argument constructor. No default constructor found

Dinopolis Java Coding Convention

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Lecture 5: Java Fundamentals III

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

TypeScript for C# developers. Making JavaScript manageable

Web Development in Java

AP Computer Science Java Subset

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

bbc Developing Service Providers Adobe Flash Media Rights Management Server November 2008 Version 1.5

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Mail User Agent Project

3 Improving the Crab more sophisticated programming

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Lecture J - Exceptions

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Computer Programming C++ Classes and Objects 15 th Lecture

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Moving from CS 61A Scheme to CS 61B Java

Install Java Development Kit (JDK) 1.8

If you wanted multiple screens, there was no way for data to be accumulated or stored

Explain the relationship between a class and an object. Which is general and which is specific?

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Object Oriented Software Design II

Visual Basic Programming. An Introduction

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Tutorial: Getting Started

Specialized Programme on Web Application Development using Open Source Tools

Java SE 8 Programming

ECE 122. Engineering Problem Solving with Java

To Java SE 8, and Beyond (Plan B)

13 Classes & Objects with Constructors/Destructors

Java from a C perspective. Plan

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

The C Programming Language course syllabus associate level

Chapter 13 - Inheritance

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Lecture 1 Introduction to Android

Software Engineering Techniques

Web development... the server side (of the force)

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

BPM Scheduling with Job Scheduler

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Delphi Developer Certification Exam Study Guide

1 of 1 24/05/ :23 AM

CISC 181 Project 3 Designing Classes for Bank Accounts

Syllabus for CS 134 Java Programming

Debugging Java Applications

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

A deeper look at Inline functions

Specialized Programme on Web Application Development using Open Source Tools

OpenCL Static C++ Kernel Language Extension

1 Posix API vs Windows API

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CSE 308. Coding Conventions. Reference

Pemrograman Dasar. Basic Elements Of Java

Software quality improvement via pattern matching

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

Beyond the Mouse A Short Course on Programming

Storage and linkage specifiers

An Overview of Java. overview-1

Java Crash Course Part I

C Coding Style Guide. Technotes, HowTo Series. 1 About the C# Coding Style Guide. 2 File Organization. Version 0.3. Contents

Konzepte objektorientierter Programmierung

POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful

Building a Multi-Threaded Web Server

FLORIDA STATE COLLEGE AT JACKSONVILLE COLLEGE CREDIT COURSE OUTLINE. Introduction to Programming with Visual Basic.NET

Java the UML Way: Integrating Object-Oriented Design and Programming

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Concepts and terminology in the Simula Programming Language

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Writing Self-testing Java Classes with SelfTest

Transcription:

Introduction Tuesday 31 July

1 2 3 4 5 6 7 8 9

Composit are used in nearly every language. Some examples: C struct Pascal record Object Oriented - class

Accessing data are containers for (one or) several other values. This is a way to create a hierarchy for data in memory. A basic example of a set of variables that belong together is: person age, person fname, person lname It is possible to join them under a common variable. This way person has three attributes, namely: age, fname, lname. In these can be accessed via punctation, as: person.fname + " is " + person.age + " old."

Objects The advantage of this is structure. Instead of having person1 age, person2 age, etc., only person1 and person2 is needed. the rest of the data is hidden inside them. Since each variable can be seen as an object, as the person being an object owning it s age, which is a type of object of time etc., this is the base for Object Oriented languages.

Classes An object is an instance of a class during run time. This is what the programmer interact with when the program is executed. A class is a composite type with devoted functions (methods). This is the drawing the programmer constructs for the data handling. A class is what states that there is an attribute named age. An object is the chunk of data accually having the attribute s value.

More comparisons An object could be compared with a box containing notes (attributes): A note with a primitive value. A note with the number of another box (reference). Not in the scope of this course: Another box (inheritance)

Hierarchy Each type of class has a set of methods ( functions) it can perform. If the method is unsupported by the class, the method will be called in the next class in the hierarchy. (More on this subject later during the course)

Naming conventions Naming Convention used by Sun: class Noun Composed words All words have initial capital E.g. CarEngine

Naming conventions Naming Convention used by Sun: method Composed words All words except the first have initial capital E.g. domagic()

Naming conventions Common prefixes in a method name: isxxx() - return boolean if true setxxx(value) - Set value of XXX getxxx() - Get value of XXX Less common/more specific: addxxx() - Add a value to some kind of list/set removexxx(value) - Remove an element from a list/set doxxx() - Execute a specific task

Visibility modifiers for classes: Visibility private only reachable from the same class no modifier also the same package protected also through inheritance public from any class Only private and public of interest in this course. The reason why anyone should use for instance private is to hide accessibility to other classes. This way error handling is made much easier, since a private method only will be called from the same class. This also eases re-writing of code. If all methods were public, the entire program would have to be checked.

syntax looks and behaves a lot like C/C++. Therefore a lot of the following examples would be close to identical in the three languages.

while while( condition ) { // code block Execute the code block iff the condition is true, repeat until condition is false.

do... while do { // code block while( condition ); Execute the code block, then repeat iff the condition is true.

statement_a; while( condition ) { // code block statement_b Could be written as: for for( statement_a ; condition ; statement_b) { // code block Example: for( int i = 0 ; i < 100 ; i++) { // code block

I/O For the sake of example creation Standard output send text to the console: System.out.print("Print this"); System.out.println("Print this"); Standard error send text unbuffered to the console: System.err.print("Print this"); System.err.println("Print this"); Also, System.in exists, which can be used to read text from the console.

I/O in JSP In JSP the variable out can be used to send text to the browser. For instance: out.println("hello World!");

- MyNumber class MyNumber { // Member variable, default value = 0 private int number = 0; // Set the value of the number public void setnumber(int number) { this.number = number; // Get the value of the number public int getnumber() { return number;

Explanation of MyNumber private int number = 0; A private variable, which means it s reachable from within the class itself, but not from the outside. The value is set to 0 as soon as the object is created.

Explanation of MyNumber public void setnumber(int number) { this.number = number; A public method, reachable from everywhere were this object is known. Will set the number of the member variable (this is used since there are several variables with the same name) to the given value.

Explanation of MyNumber public int getnumber() { return number; A public method, reachable from everywhere were this object is known. Will get, and return, the number of the member variable. number.

MyNumber class MyNumber { // Member variable, default value = 0 private int number = 0; // Set the value of the number public void setnumber(int number) { this.number = number; // Get the value of the number public int getnumber() { return number;

Using MyNumber(1) class MyMax { // Starting value private MyNumber maxnum = new MyNumber(); // Update the value of the number public boolean addnumber(mynumber number) { if (maxnum.getnumber() < number.getnumber()) { maxnum.setnumber(number.getnumber()); return true; return false;

Using MyNumber(2) // Get the value of the number public int getmaxnumber() { return maxnum.getnumber();

A constructor is the method first runned in an object. When using new MyNumber() there were no constructor defined, and therefore nothing was runned. We can create a constructor as: public class Merlin { public Merlin() { System.out.println("No arguments"); public Merlin(int a) { System.out.println("Argument given: " + a); This enables new Merlin() as well as new Merlin(4) ;

Over Several methods (for example constructors) can co-exist with the same name, as long as they have different arguments. This is called over.

An interface is a content list of required methods. This way you could know that a certain method is implemented if the class implements the interface. Could be compared with a content -list on the outside of the box, guarenteeing some variabler/methods to exist.

example public interface Magician { public void domagic(); public class Merlin implements Magician { public void printname() { System.out.println("My name is Merlin"); public void domagic() { System.out.println("Abracadabra");

A class is, as well as itself, a version of it s parents and all interfaces. Merlin is both Merlin and a Magician. Therefore we could use Merlin as a Magician only, if we want. Magician m = new Merlin(); m.domagic(); m.printname(); //<- Will result in a compile error // A Magician is not Merlin

All objects are at least an Object. Test any polymorphic match with instanceof. Object m = new Merlin(); if(m instanceof Magician) System.out.println("We have a magician!"); if(m instanceof Merlin) System.out.println("The magician is Merlin.");

Typecasting If you are sure a class implements a certain interface you could typecast it. This will force the object to be handled as the given one. Typecasting is done by giving the target type within parenthesis before the variable. Object m = new Merlin(); if(m instanceof Merlin) ((Merlin)m).printName(); if(m instanceof Magician) ((Magician)m).doMagic();

Structuring the code Ten or more classes can lead to problems with colliding names and differences between classes becoming hard to remember. There s a need for structure between classes.

is defined with the keyword package, for instance: package fantacy; public class Merlin implements Magician { //...

Importing To use an external package or parts from it, use the keyword import. A trailing wild card will enable usage of all classes in the package. An alternative is to only define one class. import fantacy.*; import java.util.linkedlist;... Object m = new Merlin(); LinkedList l = new LinkedList(); This goes for classes as well as interfaces. By convention, a reversed domain name is used, for instance se.umu.cs.doa.*, which will enable usage of all classes in se.umu.cs.doa directly.

Classpath The packages are searched for in the same order as the classpath contains them. The API comes last. Classes could also be used by calling them directly, as: java.util.linkedlist l = new java.util.linkedlist(); If you have a hierarchy in your classpath, each. should mean a sub directory of. This means that se.umu.cs.doa.aclass would be placed in: SOMEDIR/se/umu/cs/doa/AClass.java, the package of AClass should be se.umu.cs.doa and SOMEDIR should be added to your classpath.

ARchives A set of directories in the base of a classpath (for instance SOMEDIR in the previous slide) can be packed into a JAR-file ( ARchive). A JAR-file is a special ZIP-file with a Manifest, an explanation of the archive. The manifest could also include user-specified fields readable by the application. These archives can be added to the classpath.

To load a class in a dynamic way, we use code like: try { Class c = getclass(); Object m = c.forname("merlin").newinstance(); catch (Exception e) { e.printstacktrace(); Ignore the try... catch until the next slide. This loads the class with the given name, and creates a new object (instance) of it.

What about try... catch? try... catch When something goes wrong, we can throw an exception. It is a small object used only to identify an error. If an exception is created and thrown in a method, the parent (caller) must either handle it, or throw it to it s parent. If a method could throw (or pass on) an exception, it must be specified in the declaration. public void domagic() throws OutOfMagicDustException {...

Using try... catch If you want to handle a throwed exception you must use try... catch. The try-block will be executed, and as soon as an exception is thrown, it s aborted, and the correct handler (prioritized from the top down) will be runned. The first polymorphic match will be used. This means you can have several catch-blocks. try { m.domagic(); anotherobject.setstuff(2); catch (OutOfMagicDustException oomde) { oomde.printstacktrace(); catch (StuffReadOnlyException sroe) { sroe.printstacktrace();

Runtime Exceptions Some exceptions may be thrown without notice. For instance NullPointerException, which means you didn t initialize something properly before using it, or ArithmeticException when dividing something by zero. These exceptions can be catched as well. To catch all exceptions, use their most common polymorphic form, the interface Throwable. catch (Throwable t) {

What Classes and Objects are. Seen some examples of simple classes. Talked about constructors. How objects can be seen as more general ones with polymorphism. What an interface is, and how (and for what) it can be used, and its connection to polymorphism., classpath, dynamic class. Error handling.