G 54 PRG Programming Lecture 15 Classes Objects
G 54 PRG Programming Lecture 15 Classes & Objects: Examples Amadeo Ascó Adam Moore 1
Previously • Methods – Arguments – Return – Types • Constructors Amadeo Ascó , Adam Moore 2
Review • Classes consist of: – Data • Variables / members / properties – Functionality • Methods - which optionally accept arguments and return values • Instances of classes are called objects • Instance Variables / Methods – The default – One copy for each instance of the class • Class Variables / Methods – static – One copy shared by all instances of the class Amadeo Ascó , Adam Moore 3
Overview • • • Data Hiding Access Control Class Methods Abstract Classes Understanding Hello World Amadeo Ascó , Adam Moore 4
Data Hiding • Class and instance variables can be accessed from anywhere providing the full object or class name is used. • Variables declared in a method are “hidden” – Local to that method – (scope and scoping) Amadeo Ascó , Adam Moore 5
Access Control • Methods, classes and variables may be given modifiers to indicate how they may be used. – static - used to indicate a class variable – public – private • Public Methods – This is the default. Public methods may be used anywhere (providing the full class/object name is used). • Private Methods – Access is restricted to the class that contains the method. Amadeo Ascó , Adam Moore 6
Class Methods • Class methods (like class variables) have the static modifier. • This means that they can be used without instantiation. static int squared(int i) { return i*i; } • Classes that are not allowed to be instantiated are abstract classes. Amadeo Ascó , Adam Moore 7
Abstract Classes • Abstract classes are declared with the abstract modifier. • Abstract classes may not be instantiated. • Abstract classes serve to hold static variables and methods. • This is often useful for libraries of predefined functionality. Amadeo Ascó , Adam Moore 8
Understanding Hello World This class is called Hello The main method is a class method The main (i. e. method The is be public main (i. e. method does not return any The main method has a parameter The Hello class contains a data it can accessed without accessiblecreating outsidean of the class of Hello) method called mainargs (an array of String) instance Hello) class Hello { public static void main (String[] args) { System. out. println(“Hello World!”); } } Amadeo Ascó , Adam Moore 9
- Slides: 9