Xtend Programming Language

Size: px
Start display at page:

Download "Xtend Programming Language"

Transcription

1 Xtend Programming Language Produced by: Eamonn de Leastar Department of Computing and Mathematics

2 Agenda Subtitle Excellent Xtend User Guide (Version 2.6) API Docs (version 2.8) In Xtend everything is an expression and has a return type. Statements do not exist. 2

3 Hello World xtend class HelloWorld def static void main(string[] args) println("hello World") java public class HelloWorld public static void main(string[] args) System.out.println("Hello World"); 3

4 Relevant XTend Features (for pace-consolextend) Java Interoperability Type Inference Conversion Rules Classes Constructors Fields Methods Override Inferred return types Expressions Literals Casts Field access & method invocation Constructor call Lambda Expressions If expression switch Expression return 4

5 Type inference Xtend and Java statically typed language (type checking done at compile time). Supports Java's type system i.e. primitive types, arrays all Java classes, interfaces, enums and annotations that reside on the class path. With Java, you are forced to write type signatures over and over again it s not a problem of static typing but simply a problem with Java. Although Xtend is statically typed just like Java, you rarely have to write types down because they can be computed from the context. 5

6 public static void main(string[] args) List<String> names = new ArrayList<String>(); names.add("ted"); names.add("fred"); names.add("jed"); names.add("ned"); System.out.println(names); Erase e = new Erase(); List<String> short_names = e.filterlongerthan(names, 3); System.out.println(short_names.size()); for (String s : short_names) System.out.println(s); def static void main(string[] args) var names = new ArrayList<String>() names.add("ted") names.add("fred") names.add("jed") names.add("ned") System.out.println(names) var e = new Erase() var short_names = e.filterlongerthan(names, 3) System.out.println(short_names.size()) for (s : short_names) System.out.println(s) Type inference Java XTend 6

7 public static void main(string[] args) List<String> names = new ArrayList<String>(); names.add("ted"); names.add("fred"); names.add("jed"); names.add("ned"); System.out.println(names); Erase e = new Erase(); List<String> short_names = e.filterlongerthan(names, 3); System.out.println(short_names.size()); for (String s : short_names) System.out.println(s); def static void main(string[] args) var names = new ArrayList<String>() names.add("ted") names.add("fred") names.add("jed") names.add("ned") System.out.println(names) var e = new Erase() var short_names = e.filterlongerthan(names, 3) System.out.println(short_names.size()) for (s : short_names) System.out.println(s) Type inference Java XTend 7

8 Conversion Rules In addition to Java's autoboxing to convert primitives to their corresponding wrapper types (e.g. int is automatically converted to Integer when needed), there are additional conversion rules in Xtend. Arrays are automatically converted to List<ComponentType> when needed and vice versa. This is valid Xtend code: def tolist(string[] array) val List<String> aslist = array return aslist Subsequent changes to the array are reflected by the list and vice versa. Arrays of primitive types are converted to lists of their respective wrapper types. Conversion works the other way around too, similar to Java s unboxing: all subtypes of Iterable are automatically converted to arrays on demand. 8

9 Relevant XTend Features (for pace-consolextend) Java Interoperability Type Inference Conversion Rules Classes Constructors Fields Methods Override Inferred return types Expressions Literals Casts Field access & method invocation Constructor call Lambda Expressions If expression switch Expression return 9

10 Classes At a first glance an Xtend file pretty much looks like a Java file. It starts with a package declaration followed by an import section and class definitions. The classes in fact are directly translated to Java classes in the corresponding Java package (see the xtend-gen folder). package acme.com import java.util.list class MyClass String name new(string name) this.name = name An Xtend class can have constructors, fields, methods and annotations. def String first(list<string> elements) elements.get(0) 10

11 Class Declaration The class declaration reuses a lot of Java's syntax but still is a bit different in some aspects: All Xtend types are public by default. Xtend supports multiple public top level class declarations per file. Each Xtend class is compiled to a separate top-level Java class. Abstract classes are defined using the abstract modifier as in Java. 11

12 Constructors An Xtend class can define any number of constructors. Unlike Java you do not have to repeat the name of the class over and over again, but use the keyword new to declare a constructor. Constructors can also delegate to other constructors using this() in their first line. class MyClass String name new(string name) this.name = name def String first(list<string> elements) elements.get(0) class MySpecialClass extends MyClass new(string s) super(s) new() //delegating to the first constructor above this("default") 12

13 Fields A field can have an initializer. Final fields are declared using val, while var introduces a non-final field (and can be omitted). If an initializer expression is present, the type of a field can be inferred only if val or var was used to introduce the field. The keyword final is synonym to val. Fields marked as static will be compiled to static Java fields. The default visibility for fields is private. You can also declare it explicitly as being public, protected, package or private. class MyDemoClass int count = 1 static boolean debug = false var name = 'Foo' // type String is inferred val UNIVERSAL_ANSWER = 42 // final field with inferred type int 13

14 Methods Xtend methods are declared within a class and are translated to a corresponding Java method with exactly the same signature. Method declarations start with the keyword def. The default visibility of a method is public; you can explicitly declare it as being public, protected, package or private. class MyClass String name new(string name) this.name = name def String first(list<string> elements) elements.get(0) def static createinstance() new MyClass('foo') 14

15 Inferred Return Types If the return type of a method can be inferred from its body it does not have to be declared. Notice also that the keyword, return, is not used. Return types must be explicit in abstract and recursive methods. def String first(list<string> elements) elements.get(0) def first(list<string> elements) elements.get(0) 15

16 Overriding Methods Methods can override methods from the super class or implement interface methods using the keyword override. If a method overrides a method from a super type, the override keyword is mandatory and replaces the keyword def. The override semantics are the same as in Java, e.g. it is impossible to override final methods or invisible methods. class MyClass String name new(string name) this.name = name def String first(list<string> elements) elements.get(0) class MySpecial extends MyClass new(string s) super(s) Overriding methods inherit their return type from the super declaration. override first(list<string> elements) elements.get(1) 16

17 Relevant XTend Features (for pace-consolextend) Java Interoperability Type Inference Conversion Rules Classes Constructors Fields Methods Override Inferred return types Expressions Literals Casts Field access & method invocation Constructor call Lambda Expressions If expression switch Expression return 17

18 Collection Literals Convenient to create instances of the various collection types the JDK offers. val mylist = newarraylist('hello', 'World') val mymap = newlinkedhashmap('a' -> 1, 'b' -> 2) Xtend supports collection literals to create immutable collections and arrays, depending on the target type. val mylist = #['Hello','World'] If the target type is an array, an array is created instead without any conversion: val String[] myarray = #['Hello','World'] An immutable set can be created using curly braces instead of the squared brackets: val myset = #'Hello','World' val mymap = #'a' -> 1,'b' ->2 An immutable map is created like this: 18

19 Type Casts A type cast behaves exactly like casts in Java, but has a slightly more readable syntax. something as MyClass 42 as Integer 19

20 Null-Safe Feature Call Checking for null references can make code very unreadable. if (myref!= null) myref.dostuff() In many situations it is ok for an expression to return null if a receiver was null. Xtend supports the safe navigation operator?. to make such code more readable. myref?.dostuff 20

21 Elvis class Person String title String firstname In addition to null-safe feature calls, Xtend supports the Elvis operator (?:) known from Groovy. The right hand side of the expression is only evaluated if the left side was null. val person = new Person(null, 'John') val salutation = person.title?: 'Sir/Madam' println(salutation) Prints Sir/Madam to the console val person = new Person( Master', 'John') val salutation = person.title?: 'Sir/Madam' println(salutation) Prints Master to the console 21

22 Variable Declarations A variable declaration starting with the keyword val denotes a value, which is essentially a final, unsettable variable. The variable needs to be declared with the keyword var, which stands for 'variable' if it should be allowed to reassign its value. Xtend val max = 100 var i = 0 while (i < max) println("hi there!") i = i + 1 Generated Java final int max = 100; int i = 0; while ((i < max)) InputOutput.<String>println("Hi there!"); i = (i + 1); 22

23 Typing The type of the variable itself can either be explicitly declared or it can be inferred from the initializer expression. Explicit declaration: the type of the right hand expression must conform to the type of the expression on the left side. var List<String> strings = new ArrayList Inferred declaration: the type can be inferred from the initializer. var strings = new ArrayList<String> 23

24 Constructor Call Constructor calls have the same syntax as in Java. The only difference is that empty parentheses are optional e.g.: new String() == new String new ArrayList<BigDecimal>() == new ArrayList<BigDecimal> If type arguments are omitted, they will be inferred from the current context similar to Java's diamond operator on generic method and constructor calls. var stringlist = new ArrayList // type will be ArrayList <String> stringlist.add("first Element") println(stringlist.get(0)) 24

25 Lambda Expressions (1) A lambda expression is basically a piece of code, which is wrapped in an object to pass it around. As a Java developer it is best to think of a lambda expression as an anonymous class with a single method. These kind of anonymous classes can be found everywhere in Java code and have always been the poorman's replacement for lambda expressions in Java. // Java Code final JTextField textfield = new JTextField(); textfield.addactionlistener(new public void actionperformed(actionevent e) textfield.settext("something happened!"); ); 25

26 Lambda Expressions (2) Xtend not only supports lambda expressions, but offers an extremely dense syntax for it. // Xtend Code val textfield = new JTextField // Java Code final JTextField textfield = new JTextField(); textfield.addactionlistener(new public void actionperformed(actionevent e) textfield.settext("something happened!"); ); textfield.addactionlistener([ ActionEvent e ]) textfield.text = "Something happened!" 26

27 Lambda Expressions (3) Lambda expression is surrounded by square brackets (inspired from Smalltalk). Also a lambda expression like a method declares parameters. The lambda here has one parameter : e which is of type ActionEvent. textfield.addactionlistener([ e textfield.text = "Something happened!" ]) You do not have to specify the type explicitly because it can be inferred from the context. 27

28 Lambda Expressions (4) Also as lambdas with one parameter are a common case, there is a special short hand notation for them, which is to leave the declaration including the vertical bar out. textfield.addactionlistener([ textfield.text = "Something happened!" ]) The name of the single variable will be it in that case. Since you can leave out empty parentheses for methods which get a lambda as their only argument, you can reduce the code above further down. textfield.addactionlistener [textfield.text = "Something happened!"] 28

29 textfield.addactionlistener(new public void actionperformed(actionevent e) textfield.settext("something happened!"); ); textfield.addactionlistener([ ActionEvent e textfield.text = "Something happened!" ]) textfield.addactionlistener([ e textfield.text = "Something happened!" ]) textfield.addactionlistener([ textfield.text = "Something happened!" ]) Java Code Xtend Code Inferred Type Shorthand for single parameter lambdas textfield.addactionlistener [textfield.text = "Something happened!"] 29 No parenthesis

30 Lambdas & Collections (1) The collections have been equipped with Extension Methods that take lambda as parameters e.g. classes ListExtensions, IterableExtensions, etc. def printall(arraylist<string> strings) strings.foreach [ s println(s) ] list.foreach[ element, index ].. // if you need access to the current index list.reverseview.foreach[ ].. // if you just need the element it in reverse order Can dramatically reduce number of loops in a program! 30

31 Lambdas & Collections (2) val strings = newarraylist("red", "blue", "green") val charcount = strings.map[s s.length].reduce[sum, size sum + size] println(charcount) Output is 12 strings.map[s s.length] The map method is in the ListExtensions class. It returns a list built using the Lambda expression i.e. Iterate through the ArrayList called strings, and for each object s found in the ArrayList, the length of the String s is added as an element to the returned List i.e. [3, 4, 5] is returned. reduce[sum, size sum + size] The reduce method is in the IterableExtensions class. It applies the function to all elements of the List [3, 4, 5] in turn i.e. given our list [3, 4, 5] and the function add (+), the result returned will be: add(add(3, 4), 5) 31

32 Switch Expression The switch expression is very different from Java's switch statement: there is no fall through which means only one case is evaluated at most. The use of switch is not limited to certain values but can be used for any object reference. Object.equals(Object) is used to compare the value in the case with the one you are switching over. switch mystring case mystring.length > 5 : print("a long string.") case 'some' : print("it\'s some string.") default : print("it\'s another short string.") 32

33 Switch Expression- Type guards Instead of or in addition to the case guard you can specify a type guard. The case only matches if the switch value conforms to this type. A case with both a type guard and a predicate only matches if both conditions match. def length(object x) switch x String case x.length > 0 : x.length // length is defined for String List<?> : x.size // size is defined for List default : -1 33

34 Relevant XTend Features (for pace-consolextend) Java Interoperability Type Inference Conversion Rules Classes Constructors Fields Methods Override Inferred return types Expressions Literals Casts Field access & method invocation Constructor call Lambda Expressions If expression switch Expression return 34

35 Active Annotations Xtend comes with ready-to-use active annotations for common code patterns. They reside in the org.eclipse.xtend.lib.annotations plug-in/jar which must be on the class path of the project containing the Xtend files. 35

36 @Accessors For fields that are annotated the Xtend compiler will generate a Java field, a getter and, if the field is non-final, a setter method. The generated methods are, by default, can be used at class level too class String name generates private String name; public String getname() return this.name; public void setname(final String name) this.name = name; 36

37 @Accessors You can use the AccessorType to change the PROTECTED_SETTER) int String internalfield PROTECTED_SETTER) private int private String internalfield public int getage() return this.age; protected void setage(final int age) this.age = age; 37

38 @Data The will turn an annotated class into a value object class. A class annotated is processed according to the following rules: all fields are final, getter methods will be generated (if they do not yet exist), a constructor with parameters for all noninitialized fields will be generated (if it does not exist), equals(object) / hashcode() methods will be generated (if they do not exist), a tostring() method will be generated (if it does not class Person String firstname String lastname 38

39 @Data class Person String firstname public class Person private final String _firstname; public String getfirstname() return this._firstname; private final String _lastname; public String getlastname() return this._lastname; public Person(final String firstname, final String lastname) super(); this._firstname = firstname; this._lastname = public int hashcode() final int prime = 31; int result = 1; result = prime * result + ((_firstname== null)? 0 : _firstname.hashcode()); result = prime * result + ((_lastname== null)? 0 : _lastname.hashcode()); return public boolean equals(final Object obj) if (this == obj) return true; if (obj == null) return false; if (getclass()!= obj.getclass()) return false; Person other = (Person) obj; if (_firstname == null) if (other._firstname!= null) return false; else if (!_firstname.equals(other._firstname)) return false; if (_lastname == null) if (other._lastname!= null) return false; else if (!_lastname.equals(other._lastname)) return false; return public String tostring() String result = new ToStringHelper().toString(this); return result; 39

40 Additional Reading: Features (1) Extension methods - enhance closed types with new functionality Lambda Expressions - concise syntax for anonymous function literals ActiveAnnotations - annotation processing on steroids Operator overloading - make your libraries even more expressive Powerful switch expressions - type based switching with implicit casts Multiple dispatch - a.k.a. polymorphic method invocation 40

41 Additional Reading: Features (2) Template expressions - with intelligent white space handling No statements - everything is an expression and has a return type Properties - shorthands for accessing and defining getters and setter Type inference - you rarely need to write down type signatures anymore Full support for Java generics - including all conformance and conversion rules Translates to Java not bytecode - understand what is going on and use your code for platforms such as Android or GWT 41

42 Features Relevant to pacemaker-console-x Extension methods - enhance closed types with new functionality Lambda Expressions - concise syntax for anonymous function literals ActiveAnnotations (@Accessors) - shorthands for accessing and defining getters and setter Powerful switch expressions - type based switching with implicit casts Type inference - you rarely need to write down type signatures anymore 42

43 Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License. For more information, please see

Produced by. Agile Software Development. Eamonn de Leastar

Produced by. Agile Software Development. Eamonn de Leastar Agile Software Development 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 Xtend Programming

More information

Produced by. Agile Software Development. Eamonn de Leastar

Produced by. Agile Software Development. Eamonn de Leastar Agile Software Development 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 Xtend Programming

More information

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar Design Patterns MSc in Computer Science 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

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Java Fundamentals (II)

Java Fundamentals (II) 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

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Object-oriented programming in...

Object-oriented programming in... Programming Languages Week 12 Object-oriented programming in... College of Information Science and Engineering Ritsumeikan University plan this week intro to Java advantages and disadvantages language

More information

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

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

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Java Classes, Inheritance, and Interfaces

Java Classes, Inheritance, and Interfaces Java Classes, Inheritance, and Interfaces Introduction Classes are a foundational element in Java. Everything in Java is contained in a class. Classes are used to create Objects which contain the functionality

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

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

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

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

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

Object-oriented programming

Object-oriented programming Object-oriented programming HelloWorld The following code print Hello World on the console object HelloWorld { def main(args: Array[String]): Unit = { println("hello World") 2 1 object The keyword object

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Produced by. ICT Skills Summer School. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Produced by. ICT Skills Summer School. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology ICT Skills Summer School Produced b Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Phsics Waterford Institute of Technolog http://www.wit.ie http://elearning.wit.ie Tping in Programming

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

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

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar 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

More information

Binghamton University. CS-140 Fall Dynamic Types

Binghamton University. CS-140 Fall Dynamic Types Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected

More information

Another IS-A Relationship

Another IS-A Relationship Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

SSE3052: Embedded Systems Practice

SSE3052: Embedded Systems Practice SSE3052: Embedded Systems Practice Minwoo Ahn minwoo.ahn@csl.skku.edu Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong

More information

Groovy Primer Chris Dail Groovy Primer (March 2010)

Groovy Primer Chris Dail  Groovy Primer (March 2010) Groovy Primer Chris Dail http://chrisdail.com Twitter: @chrisdail What is Groovy? An agile dynamic language for the Java Platform Both dynamically and statically typed Functional programming influence

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 2, 19 January 2009 Classes and

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8 Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs. Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double(3.14); 4... Zheng-Liang Lu Java Programming 290 / 321 Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

Timing for Interfaces and Abstract Classes

Timing for Interfaces and Abstract Classes Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Informatik II (D-ITET) Tutorial 6

Informatik II (D-ITET) Tutorial 6 Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

More information

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

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

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields

More information

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5, Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Programming, I. Laboratory Manual. Final Exam Solution Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Final Exam Solution

More information

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

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Interfaces. An interface forms a contract between the object and the outside world.

Interfaces. An interface forms a contract between the object and the outside world. Interfaces An interface forms a contract between the object and the outside world. For example, the buttons on the television set are the interface between you and the electrical wiring on the other side

More information

Introduction to Java https://tinyurl.com/y7bvpa9z

Introduction to Java https://tinyurl.com/y7bvpa9z Introduction to Java https://tinyurl.com/y7bvpa9z Eric Newhall - Laurence Meyers Team 2849 Alumni Java Object-Oriented Compiled Garbage-Collected WORA - Write Once, Run Anywhere IDE Integrated Development

More information

COMP 401 Spring 2014 Midterm 1

COMP 401 Spring 2014 Midterm 1 COMP 401 Spring 2014 Midterm 1 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Principles of Object Oriented Programming. Lecture 4

Principles of Object Oriented Programming. Lecture 4 Principles of Object Oriented Programming Lecture 4 Object-Oriented Programming There are several concepts underlying OOP: Abstract Types (Classes) Encapsulation (or Information Hiding) Polymorphism Inheritance

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 4 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill CSCI 136 Data Structures & Advanced Programming Lecture 3 Fall 2017 Instructors: Bill & Bill Administrative Details Lab today in TCL 216 (217a is available, too) Lab is due by 11pm Sunday Copy your folder

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited. final A final variable is a variable which can be initialized once and cannot be changed later. The compiler makes sure that you can do it only once. A final variable is often declared with static keyword

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Interfaces (1/2) An interface forms a contract between the object and the outside world.

Interfaces (1/2) An interface forms a contract between the object and the outside world. Interfaces (1/2) An interface forms a contract between the object and the outside world. For example, the buttons on remote controls for some machine. As you can see, an interface is a reference type,

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Scala. Fernando Medeiros Tomás Paim

Scala. Fernando Medeiros Tomás Paim Scala Fernando Medeiros fernfreire@gmail.com Tomás Paim tomasbmp@gmail.com Topics A Scalable Language Classes and Objects Basic Types Functions and Closures Composition and Inheritance Scala s Hierarchy

More information

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

PROGRAMMING III OOP. JAVA LANGUAGE COURSE COURSE 3 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Classes Objects Object class Acess control specifier fields methods classes COUSE CONTENT Inheritance Abstract classes Interfaces instanceof

More information

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. Inf1-OP Inheritance UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... Volker Seeker, adapting

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

COMP 401 Spring 2013 Midterm 1

COMP 401 Spring 2013 Midterm 1 COMP 401 Spring 2013 Midterm 1 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

Subtype Polymorphism

Subtype Polymorphism Subtype Polymorphism For convenience, let U be a subtype of T. Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

Mr. Monroe s Guide to Mastering Java Syntax

Mr. Monroe s Guide to Mastering Java Syntax Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.

More information

The Java Programming Language

The Java Programming Language The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information