Docsity

Java Programming: Objects, Arrays, and Containers, Slides of Java Programming

Partial preview of the text

Download Java Programming: Objects, Arrays, and Containers and more Slides Java Programming in PDF only on Docsity!

Programming Language – Java

Road Map today Java review Homework review Exception revisited Containers I/O

Object and class A class is a blueprint An object is an instance created from thatblueprint All objects of the same class have thesame set of attributes^ 

Every Person object have name, weight, height But different value for those attributes^ 

ke.name=Ke Wang, sal.name=Sal Stolfo

Class Person: illustration

Name: Ke Wangheight: 0weight: 0 Name: Salvatore J. Stolfoheight: 0weight: 0

ke sal

Class Person: variables

Name: Ke Wangheight: 0weight: 0 Name: Salvatore J. Stolfoheight: 0weight: 0

ke x sal references

objects

Arrays in Java: declaration Declaration^ 

int[] arr; Person[] persons; Also support:

int arr[]; Person persons[];

(confusing, should be avoided) Creation^ 

int[] arr = new int[1024]; int [][] arr = { {1,2,3}, {4,5,6} }; Person[] persons = new Person[50];

Arrays in Java: second kind of reference types in Java^ int[] arr = new int [5];

arr

int[][] arr = new int [2][5];

arr[0]arr[1]

arr

Reference vs. primitive Java handle objects and arrays always byreference. Java always handle values of the primitivetypes directly differ in two areas:^ 

copy value compare for equality

Static vs. non-static Static: class variable/method Non-static: instance variable/method Static ones are associated with class, notobject. Can be called using class namedirectly main() is static^ 

Even though it’s in a class definition, noinstance of the class exist when main startsexecuting

Static vs. non-static (cont.) Instance fields define an object; the valuesof those fields make one object distinctfrom another Instance method operates on an instanceof a class (object) instead of operating onthe class itself. Class methods can only use class fields;while instance methods can use bothinstance fields and class fields

Constructor Method with same name as class No return type Called automatically by new() Java provides a default one^ 

No parameter, default initialization (0/null) User can define their own^ 

The default one is gone

Method overloading Same method name and return type,different parameter list^ 

Different type, order, number… Return type is NOT enough

Inheritance Class Foo extends Bar { Can override parent’s implementation Other classes that only know Bar can useFoo as well, but not any extra methodsFoo added

polymorphism We have an array of Shapes, and we askeach Shape to draw() itself The correct method will be called^ 

The Circle’s draw() method if the Shape objectis actually Circle, Square’s draw() if it’s actuallya Square O-O term: polymorphism