CSE 8B Lecture Notes - Lecture 7: Downcasting, Member Variable, Subtyping

55 views3 pages

For unlimited access to Class Notes, a Class+ subscription is required.

Constructors and Polymorphism
Constructors
1) Have same name as Class
2) No return type
Called when an object of that type is created
o new operator creates a new object
this() same Class ctor invocation
super() immediate superclass ctor invocation
Can be overloaded
Cannot be inherited
Can have access modifiers ie. public, private, etc
Cannot have method modifiers ie. static, final, etc
Class with no ctor definitions Compiler automatically calls default no-arg ctor
Constructor Body
o this(args) Calls same Class ctor
o super(args) Calls super class ctor
Can initialize super lass’s private instane variales
o Else, compiler calls no args constructor
If the Class extends from another Class, then the Compiler will call super()
Error if super class does not have a no-arg ctor
Superclass ctors execute first, then subclass ctors on way out
this. explicitly states whether or not to use instance members or local variables/ parameters
o public class A {
private int var;
public A (int var) {
var = var; // This code does not alter member variable var
}
public int getVar() {
return this.var;
}
o }
o // in main
A a = new A(5);
a.getVar(); // This returns a 0
When a subclass ctor is called, the superclass no-arg constructor is always called in the first line
of the constructor body
o If subclass does not have a no-args ctor, then the super lass’s no-args ctor is called
o If super class does not have a no-args ctor, then there is a complier error
Polymorphism
Objects of all types come from a common superclass type
o They can all be treated as objects of that superclass type
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Homework Help
Class Notes
Textbook Notes
40 Verified Answers
Study Guides
1 Booster Class
Class+
$8 USD/m
Billed $96 USD annually
Homework Help
Class Notes
Textbook Notes
30 Verified Answers
Study Guides
1 Booster Class