Instance Members and Static Members

Similar documents
Example: Count of Points

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

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

Exercise: Singleton 1

Example: Count of Points

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

More Relationships Between Classes

First IS-A Relationship: Inheritance

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Example: Fibonacci Numbers

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

The return Statement

Recursion 1. Recursion is the process of defining something in terms of itself.

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University

Java Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University

Inheritance and Polymorphism

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

What is Inheritance?

Inheritance. Transitivity

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Inheritance (Part 2) Notes Chapter 6

Java Object Oriented Design. CSC207 Fall 2014

Programming Languages and Techniques (CIS120)

Chapter 6 Introduction to Defining Classes

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inheritance and Polymorphism

Chapter 5. Inheritance

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

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

ITI Introduction to Computing II

PROGRAMMING LANGUAGE 2

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

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

Object Orientated Programming Details COMP360

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

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

CS-202 Introduction to Object Oriented Programming

Inheritance & Polymorphism

ITI Introduction to Computing II

Written by John Bell for CS 342, Spring 2018

What are the characteristics of Object Oriented programming language?

OVERRIDING. 7/11/2015 Budditha Hettige 82

Arrays Classes & Methods, Inheritance

CMSC 132: Object-Oriented Programming II

Class, Variable, Constructor, Object, Method Questions

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

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

CS 251 Intermediate Programming Inheritance

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

Inheritance, Polymorphism, and Interfaces

G Programming Languages - Fall 2012

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

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

Inheritance (Outsource: )

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

Questions Answer Key Questions Answer Key Questions Answer Key

Computer Science 210: Data Structures

Programming overview

CS1150 Principles of Computer Science Objects and Classes

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Object-Oriented Concepts

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

COMP 250 Fall inheritance Nov. 17, 2017

Inheritance Motivation

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

VIRTUAL FUNCTIONS Chapter 10

Inheritance and Polymorphism. CS180 Fall 2007

Java Fundamentals (II)

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

Practice for Chapter 11

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Data Abstraction. Hwansoo Han

C++ (classes) Hwansoo Han

Polymorphism and Inheritance

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

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

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

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

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

C11: Garbage Collection and Constructors

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Lecture 6 Introduction to Objects and Classes

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

C10: Garbage Collection and Constructors

Inheritance (Part 5) Odds and ends

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

CS111: PROGRAMMING LANGUAGE II

C++ Important Questions with Answers

UML & OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 3 08/30/2011

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

Transcription:

Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these instance members are available only when the object is created. Those declared w/ static are static members, aka class members. Zheng-Liang Lu Java Programming 245 / 270

Zheng-Liang Lu Java Programming 246 / 270

Static Members Static members mean that there is only one copy of the static members, no matter how many objects of the class are created. The static members belong to the class, and are shared between the instance objects. They are ready once the class is loaded. They can be invoked directly by the class name without creating an instance. For example, Math.random(). Zheng-Liang Lu Java Programming 247 / 270

A static method can access other static members. However, static methods cannot access to instance members directly. (Why?) For example, 1... 2 double getdistancefrom(point p) { 3 return Math.sqrt(Math.pow(this.x p.x, 2) + Math.pow( this.y p.y, 2)); 4 } 5 6 static double distancebetween(point p1, Point p2) { 7 return Math.sqrt(Math.pow(p1.x p2.x, 2) + Math.pow(p1. y p2.y, 2)); 8 } 9... Zheng-Liang Lu Java Programming 248 / 270

Example: Count of Points 1 class Point { 2... 3 private static int numofpoint = 0; 4 5 Point() { 6 numofpoint++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument; should be placed in the first line in the constructor 11 this.x = x; 12 this.y = y; 13 } 14... 15 } Zheng-Liang Lu Java Programming 249 / 270

Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton theonlyinstance = new mysingleton (); 5 6 // Do now allow to invoke the constructor by other classes. 7 private mysingleton() {} 8 9 // Only way to obtain the singleton from the outside world. 10 public static mysingleton getsingleton() { 11 return theonlyinstance; 12 } 13 } 1 See any textbook for design patterns. Zheng-Liang Lu Java Programming 250 / 270

Garbage Collection (GC) 2 Java handles deallocation automatically. Automatic GC is the process of looking at the heap memory, identifying whether or not the objects are in use, and deleting the unreferenced objects. An object is said to be unreferenced if the object is no longer referenced by any part of your program. Simply assign null to the reference to make the object unreferenced. So the memory used by these objects can be reclaimed. 2 http://www.oracle.com/webfolder/technetwork/tutorials/obe/ java/gc01/index.html Zheng-Liang Lu Java Programming 251 / 270

finalize() Method The method finalize() conducts a specific task that will be executed as soon as the object is about to be reclaimed by GC. The finalize() method can be only invoked prior to GC. In practice, it must not rely on the finalize() method for normal operations. (Why?) Zheng-Liang Lu Java Programming 252 / 270

Example 1 public class finalizedemo { 2 static int numofpointkilled = 0; 3 4 public void finalize() { 5 numofpointkilled++; 6 } 7 8 public static void main(string[] args) { 9 double n = 1e7; 10 for (int i = 1; i <= n; i++) 11 new finalizedemo(); 12 System.out.println(numOfPointKilled); 13 } 14 } You may try different number for instance creation. The number of the objects reclaimed by GC is not deterministic. Zheng-Liang Lu Java Programming 253 / 270

HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation, stating that B exists independently from A. For example, knight sword; company employee. If A owns B, then it is a composition, meaning that B has no meaning or purpose in the system without A. For example, house room. Zheng-Liang Lu Java Programming 254 / 270

Example: Lines +2: two Point objects used in one Line object. Zheng-Liang Lu Java Programming 255 / 270

More Examples More geometric objects, say Circle, Triangle, and Polygon. Complex number (a + bi) equipped with + and so on. Book with Authors. Lecturer and Students in the classroom. Zoo with many creatures, say Dog, Cat, and Bird. Channels played on TV. Zheng-Liang Lu Java Programming 256 / 270

More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to the outside world Packages: grouping related types, providing access protection and name space management Zheng-Liang Lu Java Programming 257 / 270

First IS-A Relationship OO allows classes to inherit commonly used states and behaviors from other classes. This is called inheritance. So the classes exist in some hierarchy. A class can be declared as a subclasses of another class, which is called superclass, by using the extends keyword. Zheng-Liang Lu Java Programming 258 / 270

Hence, we can say that a subclass specializes its superclass. Equivalently, one subclass is a special case of the superclass. For example, human beings and dogs are two specific types of animals. Note that a class can extend only one other class. Each superclass has the potential for an unlimited number of subclasses. Zheng-Liang Lu Java Programming 259 / 270

Example 1 class Animal { 2 String name; 3 int weight; 4 5 Animal(String s, int w) { name = s; weight = w; } 6 7 void eat() { weight += 1; } 8 void exercise() { weight = 1; } 9 } 10 11 class Human extends Animal { 12 Human(String s, int w) { super(w, s); } 13 void writecode() { System.out.println("Write codes..."); } 14 } 15 16 class Dog extends Animal { 17 Dog(String s, int w) { super(w, s); } 18 void watchdoor() { System.out.println("Watch my door..."); } 19 } Zheng-Liang Lu Java Programming 260 / 270

The super Keyword Recall that the keyword this is used to refer to the object itself. You can use the keyword super to refer to members of the superclass. Note that this() and super() are used as the constructor of the current class and that of its superclass, respectively. Make sure all the constructor are invoked in the first line in the constructors. Zheng-Liang Lu Java Programming 261 / 270

Class Hierarchy 3 3 See Fig. 3-1 in p. 113 of Evans and Flanagan. Zheng-Liang Lu Java Programming 262 / 270

Constructor Chaining If a subclass constructor invokes a constructor of its superclass, you might think that there will be a whole chain of constructors called, all the way back to the constructor of the class Object, the topmost class in Java. So every class is an immediate or a distant subclass of Object. Recall that the method finalize() and tostring() are inherited from Object. tostring(): return a string which can be any information stored in the class. Zheng-Liang Lu Java Programming 263 / 270

Example 1 class A { 2 A() { System.out.println("A is creating..."); } 3 } 4 5 class B extends A { 6 B() { System.out.println("B is creating..."); } 7 public String tostring() { 8 return "This is inherited from Object." 9 } 10 } 11 12 public class ConstructorChainingDemo { 13 public static void main(string[] args) { 14 B b = new B(); 15 System.out.println(b); 16 } 17 } The println() method can take an object as input, and invoke tostring() method implicitly. Zheng-Liang Lu Java Programming 264 / 270

Field Hiding If one field whose name is identical to the field inherited from the superclass, then the newly field hides that of the superclass. In other words, the shadowed field of the superclass cannot be referenced by the field name. Instead, the field must be accessed through the key word super. Zheng-Liang Lu Java Programming 265 / 270

Example 1 class A { 2 int x = 1; 3 } 4 5 class B extends A { 6 int x = 2; 7 } 8 9 class FieldHidingDemo { 10 public static void main(string[] args) { 11 B b = new B(); 12 System.out.println(b.x); // output 2 13 } 14 } Zheng-Liang Lu Java Programming 266 / 270

Method Overriding The subclass is allowed to change the behavior inherited from its superclass if needed. As a subclass defines an instance method using the method name, return type, and parameters all identical to the method of its superclass, this method overrides the one of the superclass. 4 Compared to overridden methods, method overloading occurs only in the same class. Similarly if your method overrides one of its superclass s methods, you can invoke the overridden method through the use of the keyword super. 4 The static methods do not follow this rule. Zheng-Liang Lu Java Programming 267 / 270

When there are multiple implementations of the method in the inheritance hierarchy, the one in the most derived class (the furthest down the hierarchy) always overrides the others, even if we refer to the object through a reference variable of the superclass type. 5 5 An overridden method in Java acts like a virtual function in C++. See the virtual method table. Zheng-Liang Lu Java Programming 268 / 270

Example Zheng-Liang Lu Java Programming 269 / 270

Binding Association of method definition to the method call is known as binding. The binding which can be resolved at compile time by compiler is known as static binding or early binding. They are the static, private and final methods. Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. When the compiler is not able to resolve the binding at compile time, such binding is known as dynamic binding or late binding. For example, method overriding. Zheng-Liang Lu Java Programming 270 / 270