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

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

Class, Variable, Constructor, Object, Method Questions

Project 1. Java Control Structures 1/17/2014. Project 1 and Java Intro. Project 1 (2) To familiarize with

CMSC 132: Object-Oriented Programming II

1 Shyam sir JAVA Notes

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

Compaq Interview Questions And Answers

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS260 Intro to Java & Android 03.Java Language Basics

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Introduction to Programming Using Java (98-388)

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

Practice for Chapter 11

CLASSES AND OBJECTS IN JAVA

What is Inheritance?

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Java Fundamentals (II)

Programming overview

Object Oriented Programming. Java-Lecture 11 Polymorphism

Chapter 5 Object-Oriented Programming

15CS45 : OBJECT ORIENTED CONCEPTS

OVERRIDING. 7/11/2015 Budditha Hettige 82

Programming Language Concepts: Lecture 2

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

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

Programming II (CS300)

Java How to Program, 8/e

Chapter 6 Introduction to Defining Classes

Java: introduction to object-oriented features

Inheritance (continued) Inheritance

CS-202 Introduction to Object Oriented Programming

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

PROGRAMMING LANGUAGE 2

COP 3330 Final Exam Review

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

JAVA MOCK TEST JAVA MOCK TEST II

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Data Structures (list, dictionary, tuples, sets, strings)

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

final Methods and Classes

Inheritance and Polymorphism

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

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

Data Abstraction. Hwansoo Han

CMSC 132: Object-Oriented Programming II

CS111: PROGRAMMING LANGUAGE II

STRUCTURING OF PROGRAM

Java Object Oriented Design. CSC207 Fall 2014

ENCAPSULATION AND POLYMORPHISM

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

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

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

Super-Classes and sub-classes

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

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Object Orientated Analysis and Design. Benjamin Kenwright

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Inheritance and Polymorphism

Implements vs. Extends When Defining a Class

Sri Vidya College of Engineering & Technology

ECE 122. Engineering Problem Solving with Java

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

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

Classes and Inheritance Extending Classes, Chapter 5.2

Chapter 7. Inheritance

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

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

CISC370: Inheritance

CS313D: ADVANCED PROGRAMMING LANGUAGE

Instance Members and Static Members

THE CONCEPT OF OBJECT

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

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

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

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

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

Java Magistère BFA

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Java Professional Certificate Day 1- Bridge Session

Introduction to Object-Oriented Programming

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

9 Working with the Java Class Library


(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

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

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Programming II (CS300)

Object Orientated Programming Details COMP360

CO Java SE 8: Fundamentals

Software Development With Java CSCI

Inheritance. Transitivity

BBM 102 Introduction to Programming II Spring Inheritance

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

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

Transcription:

Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu Course URL: wweb.uta.edu/faculty/sharmac URL: http://itlab.uta.edu/sharma Java Java is a compiled + interpreted language (unlike most others) Javac compiles a java program into byte code (portable) JVM interprets (+ JIT compilation) the byte code on a specific machine The two step process makes it platform independent Java compiler is the same for all platforms, but a separate JVM is needed for each platform It is also possible to compile java code for a specific target machine (improves runtime efficiency, used in production systems) Java has tried to make the language OS independent E.g., timer threads, no OS calls from Java (as in C or C++) 2 Java (2) Elements of Java (classes, fields, methods) have different levels of visibility Within Class private Within Package package private (default in the absence of access modifier) Outside of package protected (including inheritence) Everywhere public Encapsulation, data/behavior hiding is important for OOD (and can be achieved in java) Minimal, need to know interfaces should be revealed User of a component should not be burdened with understanding implementation details Java class libraries (or Java APIs) provide a rich collection of existing classes Javadoc (and @params, and other annotations) facilitates understanding of existing components Classes Basic building blocks of OOD Represents a distinguishable, stand alone object Properties of the object are its fields/attributes members Operations (behavior) of the object are its methods Constructor is needed to create an object tostring()method is used to convert an object to a string (for display/print) Design includes classes and details of each class Details of a class involves deciding what members are visible, and to who (understand public, protected, default, and private from visibility viewpoint when inheritance is included) What accessor and mutator methods to implement 3 4 1

Classes (2) Instance fields versus class fields (non static versus static) Methods can return values (including reference types) A private class is not visible to any one There is no destructor in Java However, a finalize method can be defined in a class; that will be executed before the garbage collector sweeps away the object. In practice, do not rely on the finalize method for recycling any resources that are in short supply; you simply cannot know when the method is called Classes: initialization blocks Complete description of a class public class ExampleClass{ field_1; field_m; // both static and instance constructor_1 constructor_n //0 or more,no-arg as well method_1 method_k //accessor, mutator, and others //object initialization block { initialize instance fields //static fields initialization block static { initialize static fields //optional for unit testing Public static void main(string[] args){ 5 6 Initialization blocks Example public class Employee{ private static int nextid; private int id; private String name; private double salary; public Employee(String n, double s){ name = n; salary = s; public Employee(){ name = ; salary = 0; //object initialization block { id = nextid; nextid++; Loading a class A class is loaded before it can be executed (also verified) Static initialization occurs when the class is first loaded. Like instance fields, static fields are set to 0, false, and null unless you explicitly set them. All static field initializers and static initialization blocks are executed in the order in which they occur in the class declaration. You can write system.out.println( Hello World ); in your static block and it will get executed event if you do not have a main program (you will get an error after that!) Classes can also be reloaded after adding new methods //static initialization block { nextid = 1; System.out.println( Hello World! ); //compiles and prints Hello World without a main program!! 7 Behavior of classes can be changed without having to relink, reload, and restart the program (very powerful feature!) 8 2

When a default constructor is called All the data fields are initialized to their default value (0, false, or null) All field initializers and instance initialization block is executed before the constructor is executed If the first line of the constructor calls a superclass constructor (using super keyword), then the body of the super class constructor is executed If the superclass constructor is not called explicitly, the default superclass constructor is called implicitly. The body of the constructor is executed Note that it is possible to call another constructor of the same class by using this Can be used to avoid repeating code Calling another constructor of the same class public Employee(double s){ // constructor with 1 arg //calls Employee(String, double) this( Employee# + nextid, s); // constructor with 2 arg nextid++; When you call new Employee(50000), then the Employee(double) constructor calls the Employee(String, double) constructor Using the this keyword in this manner is useful you only need to write the common constructor code only once! 9 10 Final class and methods A class can be made final (in addition to other access modifiers) Final classes cannot be extended i.e., cannot act as a super class String class is a final class final class Executive extends Manager A method can also be declared as final Subclasses cannot override that method (no polymorphism) Avoids dynamic binding; hence efficient gettime and settime methods of the Calendar class are final All methods in a final class are automatically final Fields Mostly, they should be private A private field is not visible to its subclasses static if it is not needed in an instance final if its value should not be changed Fields can be primitive or reference data types (either supplied by Java or created by you) This is how you build complex objects from primitive data types and previously constructed types (or classes) 11 12 3

Fields Although Java initializes fields (not local or reference variables) with default values, it is good idea to initialize it to your default values A static field can be accessed without using an object instance You cannot use one static field to initialize another before the first one has been defined A protected field is directly visible to methods in subclasses Use it cautiously; implementation changes may become a problem if a protected filed is inherited and modified in the subclass directly Methods Are needed to provide behavior public methods are accessible from outside the class; are inherited protected methods are also inherited by subclasses even if they are in a different package; also visible in the same and inherited packages private methods can only be called from within the class; are not inherited Constructors are not inherited; always returns class type In OOP, no need to pass the object on which a method is invoked (it is available as this inside the invoked method) Pass only other arguments that are used in the method 13 14 Methods Return type need to be specified or void need to be specified static methods can be called without using an instance; they can also be called using an instance cannot override static methods in subclasses (but can hide them) Arbitrary number of arguments can be passed as the last parameters using notation they have to be of the same type They are accessed using an array inside the method They have to be the last parameters Other parameters can precede them 15 Inheritance Understand the scope of inheritance (what is inherited by subclasses and direct accessibility/visibility of members) How to form inheritance hierarchy by specializing as you define new subclasses Difference between hiding, overriding, and overloading, and shadowing How to call superclass methods of the same name (overridden methods) from a subclass How to call constructors of superclass either explicitly or implicitly by Java Clearly understand the chain of constructor calls all the way up to the Object class constructor and how instance fields are initialized Only single inheritance is supported in Java 16 4

Inheritance (2) Understand abstract classes and where and how they are used in contrast to concrete classes Abstract classes have at least one method that is not implemented there is no notion of an abstract field (only static and instance) When inherited, all abstract methods of an abstract class need to be implemented (unless the subclass is also abstract); concrete methods can be hidden and overridden (as usual) Abstract classes are useful in providing specification that should be implemented by all subclasses Can abstract classes be final? 17 Interface Similar in concept to an abstract class except that there are no concrete methods in an interface Interfaces may have constants (static, final) and method prototypes (e.g., Proj1Constants.java, Employee.java etc.,) Interfaces are implemented by a class (as opposed to extending a class for inheritance) All prototypes of an interface has to be implemented by a class that extends it (unless it is an abstract class) Any number of interfaces can be implemented by a class (as opposed to extending a single superclass) An interface cannot be instantiated (like an abstract class) Interfaces are used to specify common behavior across classes (e.g., computesalary(int) in project 3) 18 Polymorphism The ability to store subclass objects in superclass variables allows us to call a method using that variable However, the actual method invoked should belong to the class of that object (as determined at runtime) This facilitates getting different behavior for the same call at different points in time (polymorphism) persons[1] = acoach; person[1].computesalary(10) // # of on-call hours persons[1] = apmtr; person[1].computesalary(1300) // # of shares sold in that month persons[1] = anacct; person[1].computesalary(50) // # of hours worked in that month In general, I can write person[i].computesalary(n) and the system would invoke the correct method; Polymorphism (2) ArrayList<Person> persons = new ArrayList<person>(); persons.add(new Coach()); //add a coach persons.add(new accountant());//add an accountant persons.add(new Promoter()); //add a promoter Now, I can use the enhanced for statement to compute salary and print the object using polymorphism for (aperson : persons){ double sal; sal = aperson.computesalary(10); aperson.tostring(); for (aperson : persons){ double sal; if (aperson instanceof Accountant) aperson.computesalary(numhours); 19 20 5

OR Polymorphism (3) ArrayList<Person> persons = new ArrayList<person>(); persons.add(new SalesPerson()); //add a sales person persons.add(new MaintenancePerson());//add a maintenance person persons.add(new LawnCarePerson()); //add a lawn care person Now, I can use the iterator on Person to compute salary and print the object using polymorphism Iterator<Person> piter; for (Iterator<Person> piter = perosns.iterator(); persons.hasnext();){ persons.next().computesalary(20); System.println(perosns.next()); for ( int i= 0; persons.size(); i++){ System.out.println(persons.get(i)); 21 Polymorphism (4) public interface Payable { double getpayamount(); public class Invoice implements Payable {. @Override public double getpayamount(){ return public class SalariedEmployee implements Payable{ public class PayableInterfaceTest{ Payable[] payableobjects = new Payable[4]; payableobjects[0] new Invoice( ); payableobjects[2] = new SalariedEmployee( ); for (Payable currentpayable : payableobjects){ System.out.printf( %s \n%s:.2f\n\n, currentpayab;e.tostring(), Payment Due, currentpayable.getpayamount(); 22 Thank You! 23 6