Week 2 Power Point Slides

Download Report

Transcript Week 2 Power Point Slides

INHERITANCE

Definition: The ability to derive child classes (subclasses) from parent classes (super-classes)

Characteristics:
 Methods
and instance variables in the parent class
are directly accessible from child class objects
 Child classes can override parent class methods
with their own customizations
 Demonstrates the concept of reusable code. Prior
to object oriented programming, programmers
would often cut and paste sections of code. Bugs
would then show up in many places in a system
CONCEPT OF INHERITANCE
JAVA CLASS HIERARCHY

The String class


Overrides the Object class equals method
Adds a variety of its own methods
Every class inherits from the Java Object class
EXTENDING (DERIVING) A CLASS
public class Circle
{ protected double radius;
public Circle() { radius = 0; }
public Circle(double radius) {this.radius = radius;}
public double area() {return radius * radius * Math.PI;}
public String toString() {return "radius=" +radius);
}
public class Cylinder extends Circle
{ private double length;
public Cylinder(double h, double r) { super(r); length = h; }
public double volume() {return area() * length;}
public String toString() {return super.toString()+" length="+length;}
public double area() { return 2*(super.area()+Math.PI*radius*length); }
}
ACCESSING PARENT CLASS METHODS
public class Parent
{ private int size;
public Parent(int size) { this.size = size; }
public String toString() { return "size = " + size; }
public int getSize() { return size; }
Note: The getSize() method
}
of the parent class is
public class Child extends Parent
overridden in the child class
{ private int size;
public Child(int size) { super(size); this.size = 0; }
public Child(int sizeA, int sizeB) { this(sizeA); size = sizeB; }
public @Override int getSize() { return super.getSize() + size; }
public String toString() { return "size = " + getSize(); }
}
JAVA RESERVED WORDS

extends: Create a new class that is an extension of a parent class
super: Access parent class method or instance variable
this: access current class method or instance variable
instanceof: Determine if a variable is a particular child type

final: Class, method, variable cannot be extended or overridden





static: A class method or variable (one copy for all objects)
Scope Related variables/methods:




private : accessible only within class
protected: accessible within class in and to any of its child classes
public: accessible globally
Default (package friendly): accessible to all classes in the
package
STATIC METHODS AND VARIABLES
public class Demo
Static methods and variables
{ private static int x = 10;
• Go with the class, not with
private int y = 20;
individual objects.
static String out1(){ return “o1”; }• They can be accessed with dot
String out2() { return “o2”; }
notation using the class name.
• There is one copy, even if
public static void main(String[]
many objects are instantiated.
args)
{ Demo d = new Demo();
Instance variables
System.out.println(d.y+" "
• Go with each instantiated
object.
+ Demo.x +" " + x);
System.out.println(out1()
Question: What’s wrong with
+ d.out2() );
System.out.println(y)?
} }
INSTANCEOF EXAMPLE
public class Top{}
public class First extends Top {}
Note: There is an
public class Second extends Top {}
initialization block in the
public class Test
Test class
{ private Top top;
public Test()
{ if (Math.random()>0.5) top = new First();
else top = new Second();
Note: After determining the
}
class, we can cast objects
public static void main(String[] args) appropriately to access
overridden methods
{ Test test = new Test();
if (test.top instanceof First) System.out.println("First");
else System.out.println("Second");
} }
CASTING EXAMPLE
public class Test
{ public static void main(String[] args)
{ Object o = new GraduateStudent();
Output:
System.out.println(o);
Student
System.out.println( (GraduateStudent)o ); Student
System.out.println( (Person)o );
Student
System.out.println( new Person());
Person
System.out.println(new Object());
java.lang.Object@9304b1
}
}
class Person { public String toString() { return "Person"; }}
class Student extends Person
{ public String toString() { return "Student"; } }
class GraduateStudent extends Student {}
Note: Parent objects always reference overridden child methods.
Access to overridden child methods is called polymorphism
DESIGN CONSIDERATIONS





Create instance variables only when necessary. Variables local
to a single method should generally NOT be instance variables
Limit the scope of variables. In general, instance variables
should NOT be public. Use protected variables only for those
that are needed by child classes.
Static variables and methods should rarely be used.
Polymorphism (next topic) is better than relying on instanceof
Java reflection (not covered in this class) enables programs to
determine methods that exist in generic objects inheriting from
Object
THE ARRAYLIST CLASS

Arrays
 Definition:
A table of variables accessed by index
 Disadvantage: Arrays have a fixed lengh

ArrayList: A class for expandable arrays
 Advantage:
Removes array fixed length limitation
 Disadvantage: Slower to access
 Methods: add, clear, get, remove, size, set, isEmpty,
removeRange, toArray, trimToSize

Instantiate: ArrayList<String> data = new ArrayList<String>();
DEGREES AND RADIANS

Why do we need this?


We want to rotate our avatars
Java methods use radians

A radian is the radius
distance around a circle

The radius goes around the
circle 2π times
(Circumference = 2πr)

360 degrees = 2π radians


Radians = π/180 Degrees
Degrees = 180/ π Radians
THE AREA CLASS


Purpose: Enables complicated shapes that we can
transform
Question: What is a transform?



Constructors: new Area() or new Area(Shape s)




It is an operation that alters the way the area displays
Examples: scale, rotate, move (translate)
Note: Java Polygon, Rectangle, etc. are Shape objects
Method to extend an area: area.add(Area anotherArea)
Perform a transform: area.transform(AffineTransform tx);
Draw an area:
Graphics2D g2d= (Graphics2D)graphicsObject;
g2d.draw(area); or g2d.fill(area);
TRANSFORMATIONS (AFFINE TRANSFORM)




Definition: An affine transform is a manipulation of a figure
so parallel lines remain parallel
Make a transform object:
AffineTransform transform = new AffineTransform();
Edit the transform object; enable translation of coordinates,
scaling, and rotation
transform.translate(300, 300);
transform.rotate(degrees * Math.PI/180.);
transform.scale(0.5, 0.5);
Notes
 Once the AffineTransform object is configured with multiple
transforms, it is ready to be used by Area objects
 Important: The last translation is done first
 The AffineTransform class has static transform methods if only
one type of transform is needed
MAKING A SPRITE OF TWO POLYGONS
int[] x = {-100,0,100}, y = {-100,0,-100}, r = {-100,0,100}, s = {100,0,100};
Area area=new Area(new Polygon(x,y,3)), area2=new Area(new Polygon(r,s,3));
area.add(area2);
AffineTransform tx = new AffineTransform();
tx.translate(100,100);
tx.scale(0.5, 0.5);
tx.rotate(30 * Math.PI / 180.);
area.transform(tx);
area2.transform(tx);
Graphics2D g2D = (Graphics2D)g;
g2D.setColor(Color.RED);
g2D.fill(area);
area.intersect(area2);
g2D.setColor(Color.GREEN);
g2D.fill(area2);
LAB 2 HINTS
1.
2.
3.
4.
Design the figure
Determine the corresponding Java classes that inherit from Shape
(ex: Rectangle, Polygon, Arc2D.Float, Ellipse2D.Float, etc.)
Create the shape objects and call the parent Sprite add method
Sprite parent class inherits from the Area class. Its add method:
a.
b.
c.
5.
instantiates an Area object using the Shape object parameter
calls the super add method with the object just instantiated
adds the instantiated Area object and color object parameter to the
two respective array lists.
The Area class has a getBounds, intersects, and transform
methods that we will be using in this and future labs