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