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

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

Java Strings Java, winter semester

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

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

INHERITANCE. Spring 2019

TeenCoder : Java Programming (ISBN )

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Introduction to Programming Using Java (98-388)

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

CS260 Intro to Java & Android 03.Java Language Basics

Computer Science II (20082) Week 1: Review and Inheritance

1 Shyam sir JAVA Notes

Points To Remember for SCJP

Index COPYRIGHTED MATERIAL

Declarations and Access Control SCJP tips

Computer Science II (20073) Week 1: Review and Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CSC Java Programming, Fall Java Data Types and Control Constructs

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

From C++ to Java. Duke CPS

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Array. Prepared By - Rifat Shahriyar

CMSC 132: Object-Oriented Programming II

Objects and Iterators

CompuScholar, Inc. 9th - 12th grades

EMBEDDED SYSTEMS PROGRAMMING More About Languages

Inheritance. Transitivity

Brief Summary of Java

Java: introduction to object-oriented features

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Java Fundamentals (II)

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Java Overview An introduction to the Java Programming Language

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Java Exceptions Java, winter semester

The Java Programming Language

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

String is a Class; Quoted Text is an Object

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

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

STUDENT LESSON A10 The String Class

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

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

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

חומר עזר לבחינה מבוא למדעי המחשב

חומר עזר לבחינה במבוא למדעי המחשב // Indicates whether some other object is "equal to" // this one. boolean equals(object other)

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Concurrent Programming using Threads

15CS45 : OBJECT ORIENTED CONCEPTS

Object-Oriented Programming

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Introduction to Inheritance

CISC370: Inheritance

Java TM Introduction. Renaud Florquin Isabelle Leclercq. FloConsult SPRL.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

Abstract Classes and Interfaces

Course information. Petr Hnětynka 2/2 Zk/Z

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CLASS DESIGN. Objectives MODULE 4

"Hello" " This " + "is String " + "concatenation"

Java Primer 1: Types, Classes and Operators

Inheritance. The Java Platform Class Hierarchy

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Java Enum Java, winter semester ,2018 1

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

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

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

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

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

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

More on variables and methods

Selected Java Topics

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

Selected Questions from by Nageshwara Rao

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

CS 231 Data Structures and Algorithms, Fall 2016

Oracle 1Z Java Standard Edition 5 Programmer Certified Professional.

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

COE318 Lecture Notes Week 4 (Sept 26, 2011)

What is Inheritance?

9 Working with the Java Class Library

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Object Oriented Design. CSC207 Fall 2014

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture 4. Strings, Wrappers, & Containers

Class, Variable, Constructor, Object, Method Questions

Java Magistère BFA

CSC 1214: Object-Oriented Programming

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Properties of an identifier (and the object it represents) may be set at

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

VARIABLES AND TYPES CITS1001

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Transcription:

JAVA Classes

Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can be created final class cannot be extended 2

Constructor constructor object initialization declaration the same name as the class no return type modifier only visibility several constructors with different arguments selected by arguments of new class MyClass { int value; public MyClass() { value = 10; public MyClass(int v) { value = v; 3

Constructor constructor of the parent super() other constructor of the same object this() calling other constructors only as the first statement and just once parent's constructor is called always even if not explicitly called exception this() class without constructor declared has default constructor calls super() only 4

Object removal garbage collector finalize() method present in every class called before object's removal it is not a destructor like in C++ and other languages not known when it is called calling is not guaranteed object need not be removed by garbage collecting e.g. at the end of the program calls of finalize() are not chained To simplify you can forget that finalize() exists 5

Initialization of fields in constructor or direct class MyClass { int a = 5; float b = 1.2; MyClass2 c = new MyClass2(); int d = fn(); int e = g(f); // error! int f = 4;... 6

Initialization: static just once before first access or before first instance of a class is created direct static int a = 1; static initializer class MyClass { static int a; static { a = 10;... 7

Initialization: "non-static static" similar to static initializer necessary for initialization of anonymous inner classes class MyClass { int a; int b; { a = 5; b = 10;... 8

Classes: inheritance parent specification extends ParentName single inheritance single parent only class java.lang.object each class inherits from this class the only class without parent multiple inheritance only via Interfaces cast automated child to parent class A { /*...*/ class B extends A { /*...*/ A a = new B(); 9

java.lang.object Object clone() boolean equals(object obj) void finalize() Class<?> getclass() int hashcode() void notify() void notifyall() String tostring() void wait() void wait(long timeout) void wait(long timeout, int nanos) 10

Classes: visibility of members fields and methods public from everywhere (if the class is also visible) protected from the same package and children private just from the same class without a visibility modifier from the same package must be specified for each member 11

Classes: other modifiers final field constant must have initializer after initialization cannot be changed method cannot be overridden in children transient field does not belong to a persistent state of the object volatile field non-synchronized access of multiple threads no optimization can be perfomed 12

Classes: modifiers of methods abstract no method body the class must be also abstract no instance can be created method body semicolon synchronized calling thread must obtain a lock on the called object (or the class in the case the method is static) native native method implementation directly in native code for a particular platform (as an external library) method body semicolon static see the previous lecture 13

Classes: method modifiers no modifier virtual all methods are virtual static methods are not virtual public class A { public void foo() { System.out.print( A ); public class B extends A { public void foo() { System.out.print( B );... A a = new B(); a.foo(); // prints out B public class As { public static void foo() { System.out.print( A ); public class Bs extends As { public static void foo() { System.out.print( B );... A a = new B(); a.foo(); // prints out A 14

Static methods static methods are called on a class do not belong to any object class As { public static void foo() {... As.foo(); they can be called on an object (a class instance); but in reality only a type of the reference is taken value of the object is ignored type (and thus a method to be called) is determined at compile time see the previous slide 15

this reference to the object of the executed method can be used in methods and initializers only public class MyClass { private int a; public MyClass(int a) { this.a = a; 16

super access to members of the direct parent in the case S is direct parent of C ((S) this).name ~ super.name super.super cannot be used class T1 { int x = 1; class T2 extends T1 { int x = 2; class T3 extends T2 { int x = 3; void test() { System.out.println(x); // 3 System.out.println(super.x); // 2 System.out.println(((T2)this).x); // 2 System.out.println(((T1)this).x); // 1 17

super super can be used with methods too WARNING casting this does not work a code can be compiled but the same method will be called recursively class TX1 { public void foo() { /* */ class TX2 extends TX1 { public void foo() { /* */ public class TX3 extends TX2 { public void foo() { ((TX1) this).foo(); System.out.println("TX3.foo()"); 18

Java Interfaces 19

Interface only interface no implementation since Java 8, there can be an implementation can contain method headers fields inner interfaces public interface Iterator { boolean hasnext(); Object next(); void remove(); 20

Interface: fields implicitly they are public, static and final must be initialized super and this cannot be used in initialization public interface Iface { int a = 5; String s = "hello"; 21

Interface: methods without implementation implicitly abstract and public cannot be synchronized native final default methods since Java 8 contains implementation intended for extending interfaces static methods since Java 8 the same as the static methods in classes 22

Interface: inheritance multiple inheritance interface Iface1 {... interface Iface2 {... interface Iface3 extends Iface1, Iface2 {... 23

Classes and interfaces classes implement interfaces public interface Colorable { void setcolor(int c); int getcolor(); public class Point { int x,y; public class ColoredPoint extends Point implements Colorable { int color; public void setcolor(int c) { color = c; public int getcolor() { return color; Colorable c = new ColoredPoint(); 24

Classes and interfaces a class must implement all methods of its interfaces except the default methods not true for abstract classes a single method in a class can implement several interfaces interface A { void log(string msg); interface B { void log(string msg); public class C implements A, B { public void log(string msg) { System.out.println(msg); 25

Interfaces and default methods the implementation in a class has always precedence over the implementation in interfaces if implementing two interfaces with the same default method, then the method has to be implemented in the class otherwise the class cannot be compiled interface If1 { default void foo() { class Mixed implements If1, If2 { interface If2 { default void foo() { cannot be compiled 26

Java Arrays 27

Array definition array ~ object variable ~ reference int[] a; // array short[][] b; // 2-dimensional array Object[] c, // array d; // array long e, // non-array f[]; // array 28

Array initialization "static" int[] a = { 1, 2, 3, 4, 5 ; char[] c = { 'h', 'e', 'l', 'l', 'o' ; String[] s = { "hello", "bye" ; int[][] d = { { 1, 2, { 3, 4 ; 29

Array initialization dynamic int[] array = new int [10]; float[][] matrix = new float[3][3]; just several dimensions can be specified but first ones empty brackets for the rest float[][] matrix = new float[3][]; for (int i=0;i<3;i++) matrix[i] = new float [3]; // wrong int[][][][] a = new int[3][][3][]; 30

Array initialization "non-rectangular" array int a[][] = { {1, 2, {1, 2, 3, {1, 2, 3, 4, 5 ; int b[][] = new int [3][]; for (int i=0; i<3; i++) b[i] = new int [i+1]; 31

Array initialization no constructor is called elements in the created array (using new) default values references null int 0... expressions in array creation (new) fully evaluated from left int i = 4; int ia[][] = new int[i][i=3]; // array 4x3 32

Access to array array[index] indexes always 0..length-1 bounds always checked cannot be switched off exception thrown for out of bounds access ArrayIndexOutOfBoundsException array length field length int[] a = { 1, 2, 3 ; for (int i=0; i < a.length; i++) {... 33

Array ~ object int[] intarray = new int [100]; String[] strarray = new String [100]; array is object Object o1 = strarray; Object o2 = intarray; // OK // OK but Object[] oa1 = strarray; // OK Object[] oa2 = intarray; // error 34

Array ~ object Object[] oa = new Object [2]; oa[0] = new String("hello"); oa[1] = new String("world"); String[] sa1 = oa; // error String[] sa2 = (String[]) oa; // error too // can be compiled but run-time error 35

Java Strings 36

String instances of java.lang.string compiler works with them almost with primitive types String constants = instances of the String class immutable!!! for changes clases StringBuffer, StringBuilder operator + String concatenation if there is at least a single String in an expression -> all is converted to Strings and concatenated method tostring() defined in the class Object commonly overridden creates a new String 37

java.lang.string constructors String(); String(char[] value); String(byte[] bytes); String(byte[] bytes, String charsetname); String(String value); String(StringBuffer value); String(StringBuilder value); 38

java.lang.string methods int length(); char charat(int index); IndexOutOfBoundException boolean equals(object o); compares Strings == compares references String a = new String("hello"); String b = new String("hello"); System.out.println(a==b); // false System.out.println(a.equals(b)); //true 39

java.lang.string methods int compareto(string s); lexicographical comparison int comparetoignorecase(string s); int indexof(char c); int indexof(string s); return -1, if there is no such char or substring String substring(int beginindex); String substring(int beginindex, int endindex); String replacefirst(string regexp, String repl); String replaceall(string regexp, String repl); 40

Strings methods (cnt.) String join(charsequence delimiter, CharSequence... elements); since Java 8 methods can be called on String constants also String s;... if ("ahoj".equals(s)) {... 41

Java Wrapper types 42

Wrappers immutable Integer constructor Integer(int value) methods int intvalue() static int parseint(string s)... other wrapper types similarly 43

Java, winter Slides semester version 2016 J02.en.2016.01 This slides are licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 44