1 / 28

Basic -2 Classes and Objects

Basic -2 Classes and Objects. Classes and Objects. A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects: several Person instances are all around you. Trivial Example: Class Person. A Person has some properties Attributes or fields

dimaia
Télécharger la présentation

Basic -2 Classes and Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic -2Classes and Objects

  2. Classes and Objects • A class is a complex data TYPE • An object is an instance of a class. • Example: • Class: Person • Objects: several Person instances are all around you

  3. Trivial Example: Class Person • A Person has some properties • Attributes or fields • In addition it may have some behavior • methods • A java class defines properties and behavior common to all people (all Person objects) • Each person gets their own field copies

  4. Class Person - example class Person { String name; int height; // in inches int weight; // in pounds // we’ll worry about methods later void setWeight(int newWeight) { } void setHeight(int newHeight){ } }

  5. Objects • An object is an instance of a class type • An object variable is a reference to the object’s data structure • Object variable can be seen as a pointer • Declaring an object variabile != creating an object • Declaration provides a null pointer • Must create an object with the newkeyword • Calls a constructor method of the class (optionally with arguments) • Dynamic allocation Variable declaration Person p1; p1 = new Person(); p1.name = “ your name”; Object instantiation

  6. Object Variables • Multiple variables can point to same object • A variable can point to NO object • its value is null • NOTE: passing an object as parameter in a method actually passes a copy of the reference • Method manipulates the same referenced object Person p1, p2; p1=new Person(); p1.name = “John”; p2=p1; System.out.println(p1.name); System.out.println(p2.name); { Person p3; p3=new Person(); p3.name = “Dan”; p2=p3; System.out.println(p2.name); }

  7. Illustration name: “John” height: 0 weight: 0 p1 p2 name: “Dan” height: 0 weight: 0 p3 Java graciously initializes primitive fields for you

  8. Object creation caveats • What if we don’t use new? Person p; System.out.println(p.name); H:>javac Person.java Person.java:15: Variable p may not have been initialized. System.out.println(p.name); ^ 1 error

  9. Second Try Person p = new Person(); p = null; System.out.println(p.name); • Compilation works fine but … H:>java Person Exception in thread "main" java.lang.NullPointerException: at Person.main(Person.java:16)

  10. Object equality: == • RECALL: variables are references Person p1 = new Person(); Person p2 = new Person(); p1.name = “Jane”; p2.name = “Jane”; If(p1 == p2) System.out.println(“Same!"); else System.out.println(“Different!"); : Person “Jane ” p1 : Person “Jane” p2

  11. More on equality: equals() • All classes are equipped with a method equals() • For comparing objects of same class • Can be (re-)defined wrt class logic boolean equals(Person otherPerson) { if name.equals(otherPerson.name) { System.out.println(“Same!"); return true; } System.out.println(“Different!"); return false; }

  12. Object Destruction • Programmer cannot explicitly destroy an instantiated object • JVM takes care of “garbage collection” • Implicitly frees up memory from “useless” objects • Object is useless when program keeps no more references to it • e.g when program exits the context where object was created (block, method variables) • Or when variables point to other objects or are assigned the null value

  13. Let’s play around with Person … p1.weight = 200; // bad but dealable p1.weight = 700; // unfortunate, but possible p1.weight = -20; // unreal Solution: Have class modify attribute. Allows sanity checks. Provide that behavior through a method p1.setWeight(700); // OK. Weight is now 700. p1.setWeight(-20); *** Error, weight must be positive number // weight still 700

  14. Solution? … class Person { … void setWeight(int newWeight) { if (newWeight < 0) System.err.println( “*** Error, weight must be positive number”); else weight = newWeight; }

  15. … New problem p1.setWeight(-20); *** Error, weight must be positive number p1.weight = -20; // Yo, I’m the boss Assigning weight directly bypasses sanity check by the setWeight() method. We still have a problem. Solution: change attribute visibility to make the bare weight attribute inaccessible from outside Person

  16. New solution Class Person { private String name; private int height; // in inches private int weight; // in pounds public void setWeight(int newWeight) { if (newWeight < 0) System.err.println( “*** Error, weight must be positive number”); else weight = newWeight; } } Within same class no dot notation and no visibility issues

  17. New solution in action class Test { public static void main(String args[]) { Person p1 = new Person(); p1.weight = 20; } } >javac Test.java >Test.java:4: Variable weight in class Person not accessible from class Test. p1.weight = 20; ^ 1 error Denied!

  18. Finish up Need to add a getWeight(), since we can no longer access weight directly public int getWeight(void) { return weight; } Also, need get() and set() functions for name and height.

  19. Accessor Functions for Encapsulation • Generally make fields private and provide publicgetField() and setField() accessor functions. • For this course – ALWAYS • unless there’s a specific reason not to • Usually there isn’t • Need to justify explicitly otherwise! • Encapsulation keeps programs tidy • Enables clear definition of interactions between classes • Public parts of a class represents its Application Programming Interfaces (API) • Private parts hide details of the class implementation • If interface remains stable, even if implementation changes, the rest of application is unaffected • Example: height in cm. and weight in Kg.

  20. Point - float x,y + Point(float, float) + move(float dx, float dy) + String desc() More on Visibility /** Represents a 2d geometric point */ package 2d; class Point { private float x,y; // coordinates public Point(float coordX, float coordY){ x=coordX; y=coordY; } public void move(float dX, float dY){ x+=dX; y+=dY; } public String desc(){ return “Point (" + x + ", " + y + ")"; } } • Methods / Attributes • public • private • package (default) • protected Constructor with parameters At-a-glance look at the class API

  21. Constructors public class Point { private float x,y; public Point() { x=y=0; // same as default } public Point(float coordX, float coordY) { x=coordX; y=coordY; } public Point(float xy) { this(xy,xy); } } • Multiple constructors with different sets of parameters • No need to specify result type • new operator invoked with parameters matching those of some constructor • If programmer provides no constructor, Java provides default constructor (no parameters) Constructor chaining

  22. Default Constructor • Takes no parameters, initializes everything to defaults • 0, null etc. • Graciously provided by Java for absent-minded programmers ;-) • Only exists if there are no explicitly defined constructors • Any constructor, even one taking parameters, means no default

  23. Overloading • Multiple constructors is a prominent example of overloading • Multiple methods can have same name but different signatures public class Point { private float x,y; public void move(float dx, float dy){ x+=dx; y+=dy; } public void move(float dxy){ move(dxy, dxy); } }

  24. Strings • Strings in Java are objects of class java.lang.String • Java.lang is a fundamental library • String has a lot of nice features: check it out in the javadocs! char characters[] = {‘H', ‘e', ‘l', 'l', 'o'}; String salutation=new String(characters); System.out.println(salutation); System.out.println(salutation.length()); String s = “ World”; salutation += s; System.out.println (salutation);

  25. Comparing Strings • if (s1 == s2) {…. • NO! • if (s1.equals(s2)) {… • Prominent case of equals() vs. ==

  26. Turning objects into Strings • All classes have a method toString() to provide a textual description of objects • Can be (re-)defined wrt class logic public class Person { ... public String toString() { String ret; ret = name + “ is tall ”; ret += height; ret += “ inches and weighs ”; ret += weight; ret += “ pounds.” return ret; } ... }

  27. Turning objects into Strings • toString()can be invoked implicitlly • When object is used within String manipulation operations Person assistant=new Person(“Mike”); System.out.println(“the assistant is: "+ assistant);

  28. Introduction to the Java language What is Java, what is a Java program Style, Javadocs Language basics Types, variables Classes, objects, arrays Visibility and encapsulation Some utilities String, toString() System.out Summary

More Related