
















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















































Constructor this^
reference Inheritance Overloading Dynamic binding Interface Exceptions
Every Person object have name, weight, height But different value for those attributes^
ke.name=Ke Wang, sal.name=Sal Stolfo
Name: Ke Wangheight: 0weight: 0 Name: Salvatore J. Stolfoheight: 0weight: 0
ke sal
Name: Ke Wangheight: 0weight: 0 Name: Salvatore J. Stolfoheight: 0weight: 0
ke x sal references
objects
private
and provide
public
getField() and setField() accessor functions O-O term: encapsulation Private fields and methods cannot beaccessed from outside of the class.
Internal: Person.setWeight(a, 100); Invisible additional parameter to allinstance methods:
this
It holds a reference to the object throughwhich the method is invoked^
a.setWeight(100)
^ this=a
Person a=new Person(), b=new Persion();a.setWeight(100);
b.setWeight(120);
class A{
int^ w ; public void setValue (int
w ) { this. w
=^ w ; //same name! } } When a method parameter or local variable in amethod has the same name as one of the fieldsof the class, you must use this to refer to the field.
class Exp{
public int i=0;public Exp increment () {
i++;return
this ; // return current object } public static void main (String[] args){
Exp e = new Exp();int v = e.increment().increment().i; // v=2!! } }
Initialization is guaranteed All fields set to default values: primitive types to0 and false, reference to null
So the compiler know which method to call ^ Perform any necessary initialization ^ Format:
public ClassName(para){โฆ} ^ No return type, even no void!^
It actually return current object ^ Notice: if you define any constructor, withparameters or not, Java will not create thedefault one for you.
double r;public Circle (double r) {
this.r = r; //same name! } public static void main(String[] args){
Circle c = new Circle(2.0); //OKCircle c2 = new Circle(); //error!!, no more default } } Circle.java:8: cannot resolve symbolsymbol : constructor Circle ()location: class Circle
Circle c2 = new Circle(); //error!!
^
1 error
double r;public Circle(){
r = 1.0; //default radius value; } public Circle (double r) {
this.r = r; //same name! } public static void main(String[] args){
Circle c = new Circle(2.0); //OKCircle c2 = new Circle();
// OK now!
} }
Multiple constructor now!!