Java Fundamentals (II)

Similar documents
Java: introduction to object-oriented features

Java: advanced object-oriented features

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

Inheritance (Part 5) Odds and ends

Inheritance. Transitivity

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

Java Object Oriented Design. CSC207 Fall 2014

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

Abstract Classes and Interfaces

Java Magistère BFA

Class, Variable, Constructor, Object, Method Questions

INHERITANCE. Spring 2019

Introduction to Programming Using Java (98-388)

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

C#: advanced object-oriented features

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

Java and C# in Depth

CLASS DESIGN. Objectives MODULE 4

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

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

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

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

The class Object. Lecture CS1122 Summer 2008

JAVA MOCK TEST JAVA MOCK TEST II

1 Shyam sir JAVA Notes

CS260 Intro to Java & Android 03.Java Language Basics

CS-202 Introduction to Object Oriented Programming

C#: advanced object-oriented features

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

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

C12a: The Object Superclass and Selected Methods

CH. 2 OBJECT-ORIENTED PROGRAMMING

Inheritance and Polymorphism

Super-Classes and sub-classes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Object-Oriented Concepts

Index COPYRIGHTED MATERIAL

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Declarations and Access Control SCJP tips

First IS-A Relationship: Inheritance

Inheritance and Polymorphism

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

OVERRIDING. 7/11/2015 Budditha Hettige 82

Lecture 2: Java & Javadoc

For this section, we will implement a class with only non-static features, that represents a rectangle

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Programming overview

Inheritance -- Introduction

COMP 250 Fall inheritance Nov. 17, 2017

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

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Implements vs. Extends When Defining a Class

What is Inheritance?

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

CMSC 132: Object-Oriented Programming II

More Relationships Between Classes

Introduction to Inheritance

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

COP 3330 Final Exam Review

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

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

Operators and Expressions

Example: Count of Points

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

15CS45 : OBJECT ORIENTED CONCEPTS

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

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

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

ECE 122. Engineering Problem Solving with Java

OBJECT ORİENTATİON ENCAPSULATİON

Programming Languages and Techniques (CIS120)

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

Inheritance (Part 2) Notes Chapter 6

Inheritance (continued) Inheritance

Another IS-A Relationship

Points To Remember for SCJP

Object Oriented Programming. Java-Lecture 11 Polymorphism

PROGRAMMING LANGUAGE 2

ITI Introduction to Computing II

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Java: framework overview and in-the-small features

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

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Concepts of Programming Languages

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Transcription:

Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni

static imports Introduced in 5.0 Imported static members of a class can be used as they were defined in the current class import static java.lang.math.* double r = cos(pi * theta); Issue: where does a method come from? Tip: use sparingly! 2

Command line Java To compile javac MainClass.java To execute java MainClass To generate documentation javadoc MainClass.java To generate an archive from.class files in current dir jar cf myarchive.jar *.class 3

A simple class example package ch.ethz.inf.se.java; /** * @author marco piccioni */ public class MainClass { } public static void main(string[] args) { Game mygame = new Game(); System.out.println("Game start!"); mygame.startgame(); } 4

Constructors Have the same name as the class Have no return type The no-args constructor is provided by default if no other constructor is explicitly coded 5

The keyword this Refers to the current object public class Card { private int value; } public int getvalue() { return value; } public void setvalue(int value) { this.value = value; } 6

Method overloading Using the same name with different arguments Example: constructors Method signature: name + arguments list The return type is not part of the signature Tip: overloading may be ambiguous: avoid if possible 7

Operator overloading No custom operator overloading is possible Only + for String is overloaded at language level System.out.println( Custom operator overloading + would have been nice ) 8

Method argument passing All the primitive types are passed by value Inside the method body we work with a copy We can return a value using the return keyword Object references are passed by value too, but What is passed by value is the object address In a method we can change an external object state 9

Inheritance We can explicitly extend from one class only Every class implicitly extends Object Non private inherited fields and methods can be used Upcasting happens silently Vehicle v = new Car(); Downcasting needs to be explicit Car mycar = (Car)v; 10

Polymorphism/Dynamic binding A subclass method can override a method with the same signature and return type in an ancestor class Dynamic binding is by default We can prevent overriding by using the keyword final on a method Methods cannot be overridden to be more private No overriding for static methods 11

Class Object: string representation public String tostring() { } return getclass().getname() + "@" + Integer.toHexString(hashCode()); hashcode()returns distinct integers for distinct objects Tip: All descendants should override this method Tip: The result should be a concise and easily readable informative representation 12

Object comparison public boolean equals(object obj) { return (this == obj); } The default semantics compares addresses If we need a different semantics we need to override it Implementation should satisfy an equivalence relation Reflexive, symmetric, transitive, consistent For any non null ref value x, x.equals(null) should be false It is generally necessary to also override hashcode(), because equal objects should have equal hash codes 13

Quiz Suppose to have the following method declarations in a class M. What s the compiler output? void print (int i) void print (float f) int print (float f) Suppose to have the following method declarations in a class S that extends M. What s the compiler output? void print (long f) void print (int i) 14

Quiz solution Suppose to have the following method declarations in a class M. What s the compiler output? void print (int i) //fine void print (float f) //error: duplicated method int print (float f) //error: duplicated method Suppose to have the following method declarations in a class S that extends M. What s the compiler output? void print (long f) //fine: overloading void print (int i) //fine: overriding 15

The String class Sequences of Unicode characters Immutable class: no setters If created like String s = Test ; Live in the String pool in the Stack Shared memory No copies StringBuilder provides mutable strings 16

Quiz What does it print? String s1 = 777", s2 = 777"; String s3 = new String("777"); String s4 = new String("777"); System.out.println(s1==s2+, +s1.equals(s2)); System.out.println(s1==s3+, +s1.equals(s3)); System.out.println(s3==s4+, +s3.equals(s4)); 17

Quiz solution What does it print? String s1 = 777", s2 = 777"; String s3 = new String("777"); String s4 = new String("777"); // true, true System.out.print((s1==s2)+, +s1.equals(s2)); // false, true System.out.print((s1==s3)+, +s1.equals(s3)); // false, true System.out.print((s3==s4)+, +s3.equals(s4)); By always using equals you are just fine 18

Block initializers Like methods, but without signature and return type, only curly brackets The code within them is executed during initialization Can be static or non static Useful to perform some computation before the constructors are invoked 19

Object creation process Game mygame = new Game(); 1. new allocates memory for a Game superclass instance, and performs all the following steps, until a superclass exists 2. static fields are initialized to the defaults 3. static fields are initialized to chosen values 4. static block initializers are executed 5. Non static fields are initialized to the defaults 6. Non static fields are initialized to chosen values 7. Non static block initializers are executed 8. The constructor is invoked 20

The keyword super Enables invocation of a superclass method from within an overriding method in a subclass Can be used to explicitly invoke a constructor of the superclass (see next example) 21

Chained constructors A constructor body implicitly starts with a call to the parent no-args constructor A specific constructor may be invoked using super() Must be the first instruction public class CreatureCard extends Card { } int value; public CreatureCard(String name){ super(name); //specific initializations value=7; } 22

The final modifier On a class Cannot be inherited from On an attribute or local variable It s a constant, cannot be reassigned and must be initialized If it s a reference, object state can be changed Style tip: constants are capitalized On a method Cannot be overridden 23

Shadowing Variables with the same names in different scopes: A local variable shadows an attribute with the same name: use this to access the attribute A superclass attribute shadows a subclass attribute with the same name Does not trigger polymorphism: if reference is superclass type and attached object is subclass type, the superclass variable is used Tip: avoid is possible (may be confusing) 24

Abstract classes An abstract class is a class declared as abstract Cannot be explicitly instantiated If we declare a method abstract, the enclosing class has to be declared abstract Useful for conceptualization 25

Quiz Can an abstract class have no abstract methods? Can an abstract class have more than one superclass? Can an abstract class be a subclass of a concrete class? Are an abstract class constructors invoked during the initialization process? 26

Quiz solutions Can an abstract class have no abstract methods? Yes Can an abstract class have more than one superclass? No, single inheritance holds Can an abstract class be a subclass of a concrete class? Yes, think that Object is a concrete class Is an abstract class constructor invoked during the initialization process? Yes 27