This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
! A class is a data type, and data typesdefine a range of values. So what arethe values of class type?! Objects
! An object is an instance of a class. E.g.,where Point is a class representing allpossible points a Point objectrepresents a specific point in 2 dims.
public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}
public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}
public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}
It has 2 fields named x andy, both of double type.
They are public, i.e., directlyavailable to anyone holding areference to an object of typePoint.
public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}
It has a constructor thattakes in 2 parameters (alsocalled x and y)
public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}
this.x refers to the field x, where as x (on theright hand side of the assignment) is the x fromthe parameter list).
this is a reference to the object beinginstantiated (almost true ;-), but good enoughfor now).
We only need this because the field and theparameter is called the same.
public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}
A method called distanceFromOrigin, whichtakes in no parameters and returns _____!x2+y2
! Where instance of a class (I.e., object)has instances of instance fields, a classfield is shared between instances:public class Point { static int counter = 0;
Public class Point { int x, y; static int count = 1; Point (int x, int y) { this.x = x; this.y = y; count += 1; }} A CLASS
x = 4y = 3new Point(4,3);
AN OBJECT
• this.x = x initializes the instance field x to the value of the parameter x (4)•this.y = y initializes the instance field y to the value of the parameter y (3)•count += 1 increments the class field by one.
! Within the class in which a static field isdeclared, it may be referenced by itsname:public class Point { static int counter = 0; int getCouner() { return counter; }
public static int getInstanceCount() { return counter; }}
Constructor
A constructor is invokedas the first thing that happensat the new Point(…,…) call. It is used to set up fieldsin the object. new Point(…,…) does not return a referenceto the new object until the constructor has run.
public static int getInstanceCount() { return counter; }}
Object Context
this is a special referencevalue that always referesto the object that we are currently operating inside.Here we use it to get to thefields as they are overshadowedby the parameters.
public static int getInstanceCount() { return counter; }}
Accessor Method
Since counter is private in Point,we cannot access it throughPoint.counter orp.counter for any object p of class Point, so we need a wayto get to the value of counter.This is called an accessor method..
Might be nice to make x and y private as well, but then we need accessors (also called ‘getters’) for them, and if we want to changethem we need mutators (also called ‘setters’) as well.
public class Circle { // a class field public static final double π = 3.14159; // an instance field public double r; // the radius of the circle public Circle(double radius) { r = radius; } public double area() { return π * r * r; } public double circumference () { return 2 * π * r; }}
public class Circle { // a class field public static final double π = 3.14159; // an instance field public double r; // the radius of the circle public Circle(double radius) { r = radius; } public double area() { return π * r * r; } public double circumference () { return 2 * π * r; }}
Can I add this method:public static getRadius() { return r;}
! A special keyword ‘this’ can bereferenced inside objects. It refers to thecurrent context, that is, the object inwhich the code is located (NOT class,but object)
public class Circle { public static final double π = 3.14159; private double radius; public Circle(double radius) { // set the radius field equal to the radius parameter } public double getRadius() { return radius; } public double area() { return π * radius * radius; } public double circumference() return 2 * π * radius; } public static double radToDeg(double rads) { return rads * 180 / π; }}
public class Circle { public static final double π = 3.14159; private double radius; public Circle(double radius) { // set the radius field equal to the radius parameter } public double getRadius() { return radius; } public double area() { return π * radius * radius; } public double circumference() return 2 * π * radius; } public static double radToDeg(double rads) { return rads * 180 / π; }}
Problem: both the field and theparameter is called radius.
public class Circle { public static final double π = 3.14159; private double radius; public Circle(double radius) { // set the radius field equal to the radius parameter } public double getRadius() { return radius; } public double area() { return π * radius * radius; } public double circumference() return 2 * π * radius; } public static double radToDeg(double rads) { return rads * 180 / π; }}
Problem: both the field and theparameter is called radius.
Solution: The field can be referenced like any other public field by:objectRef.fieldNameBut we don’t have an object reference do we?Yes we do, it is called ‘this’
public class Circle { public static final double π = 3.14159; private double radius; public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public double area() { return π * radius * radius; } public double circumference() return 2 * π * radius; } public static double radToDeg(double rads) { return rads * 180 / π; }}
Problem: both the field and theparameter is called radius.
Solution: The field can be referenced like any other public field by:objectRef.fieldNameBut we don’t have an object reference do we?Yes we do, it is called ‘this’
! Let us start by an example.! A “vehicle” can be a car, a truck, a motor
cycle, a bike, a scooter etc. What do allthose things have in common?! Wheels! Color! ….
Inheritance
! Let us design a class for a vehicle:public class Vehicle { private int wheels; private String color; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
Inheritance
! We can break the list of all vehicles intothe motorized ones and the ‘manual’ones; we could draw a diagram like this:
! All motorized vehicles are vehicles, andall manual vehicles are vehicles.
Vehicle
ManualVehicleMotorizedVehicle
Inheritance
! We could define separate classes forMotorizedVehicle and ManualVehicle:
public class MotorizedVehicle { private int wheels; private String color; private int cc; public MotorizedVehicle( int wheels, String color, int cc) { this.wheels = wheels; this.color = color; this.cc = cc; } …}
public class ManualVehicle { private int wheels; private String color; private boolean hasSeat; public ManualVehicle(int wheels, String color, boolean hasSeat) { this.wheels = wheels; this.color = color; this.hasSeat = hasSeat; } …}
Inheritance
! We could define separate classes forMotorizedVehicle and ManualVehicle:
public class MotorizedVehicle { private int wheels; private String color; private int cc; public MotorizedVehicle( int wheels, String color, int cc) { this.wheels = wheels; this.color = color; this.cc = cc; } …}
public class ManualVehicle { private int wheels; private String color; private boolean hasSeat; public ManualVehicle(int wheels, String color, boolean hasSeat) { this.wheels = wheels; this.color = color; this.hasSeat = hasSeat; } …}
Both classes have These fields, BECAUSE they areboth Vehicles.
Inheritance
! We could define separate classes forMotorizedVehicle and ManualVehicle:
public class MotorizedVehicle { private int wheels; private String color; private int cc; public MotorizedVehicle( int wheels, String color, int cc) { this.wheels = wheels; this.color = color; this.cc = cc; } …}
public class ManualVehicle { private int wheels; private String color; private boolean hasSeat; public ManualVehicle(int wheels, String color, boolean hasSeat) { this.wheels = wheels; this.color = color; this.hasSeat = hasSeat; } …}
Both constructors execute partiallythe same code; The initializationOf the fields they have in commonlook alike.
Inheritance
! Perhaps we could redraw the picturefrom before:
Vehicle
MotorizedVehicle
Vehicle
ManualVehicle
Vehicle
! We can imagine aMotorizedVehicleconsisting of aVehicle plussome new stuff.
Inheritancepublic class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public getCc() { return cc; }}
public class Vehicle { private int wheels; private String colour; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
Inheritancepublic class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public getCc() { return cc; }}
public class Vehicle { private int wheels; private String colour; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
To inherit the fields and methodsfrom the super class we use the keyword extends.
Inheritancepublic class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public getCc() { return cc; }}
public class Vehicle { private int wheels; private String colour; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
A super class’ constructor must beexecuted as well. Either explicitlyusing the keyword super, or implicitly(by not putting anything, in which case the default constructor of the super class gets called)
Inheritance
! What happens when we do:MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);
Inheritance
! What happens when we do:MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);
! Object for a MotorizedVehicle is created.
int cc
MotorizedVehicleobject
Inheritance
! What happens when we do:MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);
! Object for a MotorizedVehicle is created.! Object for Vehicle is created.
int cc
MotorizedVehicleobject
int wheelsString color
Vehicle object
Inheritance
! What happens when we do:MotorozedVehicle mv = new MotorizedVehicle(4,”Red”,4000);
! Object for a MotorizedVehicle is created.! Object for Vehicle is created.! Constructor for Vehicle
is executed throughsuper(4,”Red”)
! Rest of the constrctorfor MotorizedVehicleis executed.
int cc
MotorizedVehicleobject
int wheelsString color
Vehicle object
4
“Red”4000
Inheritance
! Since mv is a MotorizedVehicle thatinherits for Vehicle, all of the followingare legal:! mv.getwheels();! mv.getColor();! mv.getCc();
! But only public methods may be invokedfrom outside the object.
Inheritance
! In addition, if Vehicle has a privatemethod, then it cannot be invoked fromMotorizedVehicle.
public class A { private void foo() { … }}public class B extends A { public void bar() {
foo(); // illegal invocation }
}
Inheritance
! A class can only inherit from one otherclass. If it doesn’t inherit from any class,by default java/lang/Object is itssuper class.
! All public method and fields are inherited.! Private fields and methods are not.! Explicit constructor calls (super(..))
may only be to public constructors in thesuper class.
The Abstract Modifier
! The modifier abstract can be usedon classes and methods.!An abstract method has no body:
public abstract void foo(int x) ;!An abstract class may haveabstract methods, and a classthat has abstract methods mustbe abstract
The Abstract Modifier
! Abstract classes cannot be instantiated!What would happen if you
instantiated a class with an abstractmethod?
! A subclass of an abstract classmust also be abstract unless itimplements all un-implementedabstract methods in its classhierarchy.
The Abstract Modifier
! Example: recall this code:public class Vehicle { private int wheels; private String color; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
! We might not want to allow a Vehicleto be instantiated.
The Abstract Modifier
public abstract class Vehicle { private int wheels; private String color; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
! Though this class has no abstractmethods.
! Maybe each vehicle sub-type has aspecific string identifying it.
The Abstract Modifier
public abstract class Vehicle { private int wheels; private String color; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; }}
! A Car’s sub-type string is “car”, a motorcycle’s sub-type string is “motor cycle”.
! We need a method called getType()
The Abstract Modifier
public abstract class Vehicle { private int wheels; private String color; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; } public String getType() { return ????????; }}
! What should we return for a Vehicle?!Nothing - a vehicle doesn’t have a
type, but we must make sure all subclasses of Vehicle do.
The Abstract Modifier
public abstract class Vehicle { private int wheels; private String color; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; } public abstract String getType() ;}
! Now all subsclasses must implementgetType()
The Abstract Modifier
• We can no longer do:new Vehicle(…);
• What about the immediate subclassMotorizedVehicle? Should it beabstract? It depends• Yes, if you don’t want instances of it• No, if you want instances of it
The Abstract Modifierpublic abstract class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public abstract String getType() ; public getCc() { return cc; }}
public abstract class Vehicle { private int wheels; private String colour; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; } public abstract String getType() ;}
public class Car extends MotorizedVehicle { // fields for a car public Car(int wheels, String color, int cc, …………… ) { super(wheels,color,cc); // set the extra fields } // additional accessors public String getType() { return “Car”; }}
The Abstract Modifier
public abstract class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public abstract String getType() ; public getCc() { return cc; }}
public abstract class Vehicle { private int wheels; private String colour; public Vehicle(int wheels, String color) { this.wheels = wheels; this.color = color; } public int getWheels() { return wheels; } public String getColor() { return color; } public abstract String getType() ;}
The Abstract Modifierpublic class Arraylist<E> { private E[] elements; private int index, size;
public Arraylist() {elements =(E[]) new Object[5];index = 0;size = 5;
Transaction[transactions.size()]);transactions = new Arraylist<Transaction>(t);
The Abstract Modifierpublic class Arraylist<E> { // some internal representation of fields.
public Arraylist() { … } public Arraylist(E[] es) { … } public void add(E element) { … } public int size() { … } public E get(int index) { … } public E[] toArray(E[] es) { … }}
We don’t really care about the implementation or the internal representation,just about the public methods. (Though we do care about the constructors in Arraylist.
For the code in Account2.java all we care about is that those methods aboveare available. For all we care, any old data structure with those methods could be used.
The Interface
! We are really only interested in theinterface of the implementing class.
! As long as the class promises to makeavailable the methods we need we don’tcare about the implementation.
! We could set up a new class hierarchywhere Arraylist inherits from somecompletely abstract Collection classand use it in the Account2 class
The Interface
public class Account2 { private Collection<Transaction> transactions; private double balance; private String name; private String street; private int zip; private String state; private String city;
public void deposit(Date date, String text, double amount) { Transaction t = new Transaction(date, text, amount); transactions.add(t); balance += amount; }
. . . .}
public class Arraylist<E> extends Collection<E>{ // implement everything in Collection}public abstract class Collection<E> { public void add(E element) ; public int size() ; public E get(int index); public E[] toArray(E[] es);}
Interfaces
public class Account2 { private Collection<Transaction> transactions; private double balance; private String name; private String street; private int zip; private String state; private String city;
public void deposit(Date date, String text, double amount) { Transaction t = new Transaction(date, text, amount); transactions.add(t); balance += amount; }
. . . .}
public class Arraylist<E> implementsCollection<E> { // implement everything in Collection}public interface Collection<E> { public void add(E element) ; public int size() ; public E get(int index); public E[] toArray(E[] es);}
Classes 100% abstract are really not classes but interfaces, and should be declared in an interfacerather than a class.