Lecture 11
Fall 2018
Narges Norouzi
More survey feedback on Tuesday
access specifiers
access specifiers in inheritance
-
Subclass has access to public members of parent class
-
Public methods and properties are accessible in subclass
-
- Private members are not accessible in subclass
- What if you want to let subclasses access a member, but not other classes?
Protected member
-
Intermediate level of protection between public and private
-
Protected members accessible by
-
subclass members
-
Classes in the same package
-
access levels
Access modification in inheritance
-
You cannot reduce accessibility of methods in subclasses
-
Meaning of extends
-
Parent-granted privileges cannot be revoked/reduced by child
-
Static members
writing ebay for cars
static (1)
-
When you create a class
- You describe how objects of that class look
- And how they will behave
- You don’t actually get an object until you create one, using new
- At that point storage is allocated and methods become available.
static (2)
-
There are two situations in which this approach is not sufficient.
-
Class data or static property
-
Class method or static method
class data
-
You want to have only a single piece of storage for a particular field
-
Regardless of how many objects of that class are created
-
Or even if no objects are created
-
-
Example:
-
Altima.designYear
-
-
Class data = static properties
class method
-
If you need a method that isn’t associated with any particular object of this class.
-
You need a method that you can call even if no objects are created
-
Example:
-
Counting how many objects we created so far
-
-
Class methods = static methods
static Fields
- Static properties are shared among all the objects
- Static properties are properties of classes, not objects
-
Example:
- Player.NumberOfObjects
static methods
-
Static methods can access only static properties
-
Static methods are actually class operations
-
If a method uses only static fields, make it static!
-
Static methods are accessible via classes
-
double d = Double.parseDouble("12");
-
String s = String.valueOf(12);
-
public static void main(String[] args)
-
-
Static properties and methods are invoked on class name
example
static initialization
-
Static properties are class data, not object data
-
Constructors are created for initializing object data
-
How to initialize class data?
-
Two ways:
-
Inline values
-
Static block
-
- Static initialization is done when Class Loader loads the class
Inline initialization
static block
Initialization block
order of initialization
-
Once per class
-
Static variable declaration
-
Static block
-
-
Once per object
- variable declaration
- Initialization block
- Constructor
Zybooks chapters we covered
-
section 20.6: static member
CMPS12A - Lecture 11
By Narges Norouzi
CMPS12A - Lecture 11
- 1,484