Lecture 2: Java & Javadoc

Similar documents
Inheritance. The Java Platform Class Hierarchy

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Java Programming Tutorial 1

What is Inheritance?

Java Object Oriented Design. CSC207 Fall 2014

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

CS260 Intro to Java & Android 03.Java Language Basics

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Programming II (CS300)

Exercise: Singleton 1

Java Fundamentals (II)

Chapter 5. Inheritance

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

Chapter 5 Object-Oriented Programming

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

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

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

Inheritance and Polymorphism

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

Inheritance (Part 5) Odds and ends

CS 11 java track: lecture 3

PROGRAMMING LANGUAGE 2

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

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

CS1150 Principles of Computer Science Objects and Classes

INTERFACES. 24-Dec-10 INTERFACES VS. INHERITANCE. Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman ) Interfaces: Inheritance:

Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman )

Another IS-A Relationship

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

Index COPYRIGHTED MATERIAL

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

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

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Subtype Polymorphism

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Chapter 6 Introduction to Defining Classes

CS-202 Introduction to Object Oriented Programming

Exercise. Zheng-Liang Lu Java Programming 273 / 324

Computer Science 210: Data Structures

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Declarations and Access Control SCJP tips

Chapter 14 Abstract Classes and Interfaces

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

ITI Introduction to Computing II

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

Introduction to Programming Using Java (98-388)

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

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

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

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

CH. 2 OBJECT-ORIENTED PROGRAMMING

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Object-Oriented Concepts

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Inheritance. Transitivity

ITI Introduction to Computing II

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

Programming II (CS300)

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Chapter 15: Object Oriented Programming

Programming Exercise 14: Inheritance and Polymorphism

COP 3330 Final Exam Review

Programming overview

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

OVERRIDING. 7/11/2015 Budditha Hettige 82

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

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

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

1 Shyam sir JAVA Notes

CMSC 132: Object-Oriented Programming II

Java Magistère BFA

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Inheritance (Outsource: )

C# Programming for Developers Course Labs Contents

CS 251 Intermediate Programming Methods and Classes

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

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

More Relationships Between Classes

Lesson: Classes and Objects

Instance Members and Static Members

JAVA MOCK TEST JAVA MOCK TEST II

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

CMSC 132: Object-Oriented Programming II

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Java Classes, Inheritance, and Interfaces

Object Oriented Programming

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

Inheritance -- Introduction

First IS-A Relationship: Inheritance

Distributed Systems Recitation 1. Tamim Jabban

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

Java: introduction to object-oriented features

Transcription:

Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1

Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block Each object has its own copy of the variable! Invoked as: myobject.variablename 2

Static Variables or class variables static means constant, i.e. it will be constant for all instances of the class cannot be defined in method body Invoked as: myclass.variablename 3

Local Variables Declared in method, constructor or block Destroyed after the execution of the method No access modifier 4

Methods A collection of grouped statements that perform a logical operation and control the behavior of objects Syntax: modifier return-type method-name(type parameter-name, ){ e.g., public int enrollinclass(int classid){ Signature: method name and the number, type, and order of its parameters. Not return type Can also be static, therefore shared by all instances of a class Can be overloaded (same name, different parameters) 5

this Within an instance method or a constructor used to refer to current object can be used to call instance variables, methods, and constructors public class Car{ private String color; public Car(){ this( undefined ); public Car(String color){ this.color = color; 6

Combination of variables and methods Instance methods can access instance variables and instance methods directly. Instance methods can access static variables and static methods directly. Static methods can access static variables and static methods directly. Static methods cannot access instance variables or instance methods directly they must use an object reference. Cannot make a static reference to the non-static field in main method Static methods cannot use the this keyword as there is no instance for this to refer to. 7

Exercise: Bicycle.java Write the class Bicycle that contains the following fields: cadence gear speed id numberofbicycles Primitive types or objects? Instance variables or static? Instantiate? 8

Exercise: Bicycle.java public class Bicycle { private int cadence; private int gear; private int speed; private int id; private static int numberofbicycles = 0; 9

Exercise: Bicycle.java Write the appropriate getters and setters for these variables 10

public int getid() { return id; public static int getnumberofbicycles() { return numberofbicycles; public int getcadence() { return cadence; public void setcadence(int cadence) { this.cadence = cadence; public int getgear(){ return gear; public void setgear(int gear) { this.gear = gear; public int getspeed() { return speed; 11

Exercise: Bicycle.java Create a non-parameterized constructor that sets the id to the number of bicycles and increases the counter public Bicycle() { id = ++numberofbicycles; Create a constructor that takes 3 parameters: cadence, gear, speed. How can you use the previous constructor? public Bicycle(int cadence, int speed, int gear) { this(); this.cadence = cadence; this.gear = gear; this.speed = speed; 12

Exercise: Bicycle.java Write a main method within your class Print the total number of bicycles Create an object (unknown) using the non-parameterized constructor Print its gear field Create an object (mybike) passing the following 3 arguments (2, 3, 5). Print its speed Print the total number of bicycles 13

Exercise: Bicycle.java public static void main (String args[]) { System.out.println(Bicycle.numberOfBicycles); Bicycle unknown = new Bicycle(); System.out.println(unknown.getGear()); Bicycle mybike = new Bicycle(2,3,5); System.out.println(myBike.getSpeed()); System.out.println(Bicycle.getNumberOfBicycles()); 14

A vocabulary refresher for variables Declaration: state the type of variable and its identifier. A variable can only be declared once. E.g. int x; Initialization: the first time a variable takes a value. E.g., x = 3; Can be combined with declaration, e.g., int y = 3; Assignment: discarding the old value and replacing it with a new. x = 2; Static or instance variables are automatically initialized with default values, i.e. null for objects, 0 for int, false for boolean, etc. Local variables are not automatically initialized and your code won t compile if you have not initialized them and you are trying to use them. E.g., public void foo() { int x; System.out.println(x); //The local variable x might not have been initialized 15

Inheritance When you want to create a new class and there is already a class that includes some of the code you want your new class to have, you can derive the new class from the existing class à reuse code! We say that a class extends or inherits another class E.g., public class Car extends Vehicle Vehicle Car is a subclass of Vehicle Vehicle is a superclass of Car Car IS-A Vehicle Car 16

Inheritance in Java A subclass inherits all of the public and protected members of parent Hiding: same name of variables or of static method between super and subclass Overriding: same signature of instance methods between super and subclass Single inheritance! Vehicle A class can only extend ONE AND ONLY ONE class Multilevel inheritance Car Class SUV extends class Car which extends class Vehicle SUV 17

Example: Animal.java public class Animal { public int legs = 2; public static String species = "Animal"; public static void testclassmethod() { System.out.println("The static method in Animal"); public void testinstancemethod() { System.out.println("The instance method in Animal"); 18

Example: Cat.java public class Cat extends Animal { public int legs = 4; public static String species = "Cat"; public static void testclassmethod() { System.out.println("The static method in Cat"); public void testinstancemethod() { System.out.println("The instance method in Cat"); 19

Hiding vs Overriding public static void main(string[] args) { Cat mycat = new Cat(); mycat.testclassmethod(); //invoking a hidden method mycat.testinstancemethod(); //invoking an overridden method System.out.println(myCat.legs); //accessing a hidden field System.out.println(myCat.species); //accessing a hidden field Output: The static method in Cat\nThe instance method in Cat\n4\nCat What you were expecting, right? 20

Hiding vs Overriding public static void main(string[] args) { Animal yourcat = new Cat(); yourcat.testclassmethod(); //invoking a hidden method yourcat.testinstancemethod(); //invoking an overridden method System.out.println(yourCat.legs); //accessing a hidden field System.out.println(yourCat.species); //accessing a hidden field Output: The static method in Animal\nThe instance method in Cat\n2\nAnimal Hiding: For fields (instance+static) and methods (static) the class is determined at compile-time. Here, the compiler sees that yourcat is declared as Animal. Overriding: For instance methods this is determined at run-time. At this point, we know that yourcat is of type Cat One form of polymorphism (dynamic) 21

super keyword refers to the direct parent class of the current class super.variable (for hidden fields à avoid altogether) super.instancemethod() (for overridden methods) super(args) à to call the constructor of the superclass First line in subclass constructor 22

All classes inherit Object Directly (if they do not extend any other class) or indirectly Object class has methods (and more): public boolean equals (Object other) Default behavior returns true only if same object public String tostring() Returns string representation of object default is hexadecimal Does not print the string Typically needs to be overridden to be useful public int hashcode() Unique identifier defined so that if a.equals(b) then a, b have same hashcode 23

final variable only assigned once in its declaration or in constructor its value cannot change initialization Often paired with static, e.g., static final PI = 3.14; method cannot be overridden by subclass class - cannot be extended 24

abstract Class cannot be instantiated but can be extended Method declared without an implementation no braces and body, just semicolon public abstract int enrollinclass(int classid); If a class has at least one abstract method then it should be declared abstract itself If you extend an abstract class either declare subclass as abstract too or implement all abstract methods 25

Interfaces Contracts on how the program should work, abstracting from implementation public interface Moveable{ A class can implement many interfaces public class Car extends Vehicle implements Moveable Variables implicitly public, static, and final Methods implicitly public (abstract, default, or static) Cannot be instantiated Can extend any number of interfaces public interface GroupedInterface extends Interface1, Interface2 26

Example: Moveable interface public interface Moveable{ int turn(direction direction, double radius, double speed); default int stop(){ speed=0; public class Car extends Vehicle implements Moveable{ int turn(direction direction, double radius, double speed){ //code goes here 27

Abstract Classes vs Interfaces Can declare fields that are not static and final Can define public, protected, private concrete methods Can extend only one class whether or not abstract All fields are public, static, final All methods are public Can implement any number of interfaces 28

Nested class A class defined within a class class Outer{ static class Nested{ class Inner{ Logically groups classes that are only used once in one place Increases encapsulation Better code 29

Enum Types Example enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES Operations: int compareto(suit other) String tostring() int ordinal() returns position in its enum declaration. starts with 0 static Suit valueof(string name) static Suit[] values() returns array of all values 30

Documentation Important for code maintainability This matters even for 1 st week assignments Critical when working on a team Create documentation first this is design work! 31

JavaDoc Document generation system Reads JavaDoc comment àhtml pages http://www.quickmeme.com/meme/3ph7ed JavaDoc comment = description written in HTML + tags Enclosed in /** */ Must precede class, variable, constructor or method declaration Read the style guide 32

JavaDoc Common tags: for class: @author author name classes and interfaces @version date - classes and interfaces for method: @param param name and description methods and constructors @return value returned, if any methods @throws description of any exceptions thrown - methods 33

Packages Use them! E.g., package assignment1; before everything else Package name == folder name Helps organize large projects e.g, java.langàfundamental Import a package member: import package.member; Import an entire package: import package.*; 34

public class IdentifyMyParts { public static int x = 7; public int y = 3; What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; Question Time b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x); System.out.println("IdentifyMyParts.x = "+ IdentifyMyParts.x); 35