Classes and Objects 1
Class declaration Object creation
Structured Programming 1110/1140/6710
Copyright By PowCoder代写 加微信 powcoder
Classes and Objects 1 O1
Creating Classes and Objects
The following slides describe the mechanics of creating a class and creating objects (instances of that class) in Java.
Some of the mechanics will not make much sense until later when the relevant concepts are explained. For now, treat these as boilerplate (stuff you ‘just do’).
Structured Programming 1110/1140/6710 32
Classes and Objects 1 O1
Class Declaration
A class declaration will have the following, in order: • Anymodifiers(public,private,etc.)
• Thekeywordclass
• The class’ name (first letter capitalized)
• Optionalsuperclass’nameprecededbyextends • Optionallistofinterfacesprecededbyimplements • The class body surrounded by braces {}
Structured Programming 1110/1140/6710 33
Classes and Objects 1 O1
Member Variable Declaration
Three kinds:
• Class and instance variables, called fields
• Variables within a method, called local variables • Method arguments, called parameters
Member variables will have the following, in order: • Anymodifiers(public,private,etc.)
• The field’s type
• The field’s name
Structured Programming 1110/1140/6710 34
Classes and Objects 1 O1
Constructors
A constructor is a special method that is automatically executed when an instance is created.
Constructors differ from normal methods:
• They have no return type.
• Theyhavethesamenameastheclass.
If no constructor is provided, the compiler will automatically call the constructor for the class’ superclass
Structured Programming 1110/1140/6710 35
Classes and Objects 1 O1
Creating Objects
A statement creating an object has three parts: • Declaration (a referring variable and type)
• Instantiation(thenewkeyword)
• Initialization (call to constructor)
Structured Programming 1110/1140/6710 36
Classes and Objects 1 O1
Using Objects
Outside a class, an object reference followed by the dot ‘.’ operator must be used:
• Reference the object’s fields – Object reference, ‘.’, field name
• Call the object’s methods
– Object reference, ‘.’, method name, arguments in parentheses (‘(’ ‘)’)
Within instance methods, the object’s fields and methods can be accessed directly by name, (optionally with the this keyword).
– fieldName or methodName()
– this.fieldName or this.methodName()
Structured Programming 1110/1140/6710 37
Classes and Objects 2
Locals, globals, heap Garbage collection Initializers, access control enum types
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
Locals (stack), Globals (statics), and Heap (objects)
Local variables are declared within the scope of a method and hold temporary state. They disappear once the method returns.
Global variables (a.k.a. ‘class variables’) are declared within the scope of a class (with a static qualifier), and exist as long as the class is loaded (which is usually for the duration of the program).
Heap variables (a.k.a. ‘instance variables’) are declared within the scope of a class (without a static qualifier), and exist as long as the containing instance is reachable.
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
Garbage Collection
In some object oriented languages, the programmer must keep track of objects and delete them when they are no longer used.
This is error-prone.
Java uses a garbage collector to automatically collect objects that can no longer be used. Garbage collection approximates liveness by reachability (the collector conservatively assumes that any reachable object is live).
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
The this keyword
Within instance methods and constructors, the this keyword refers
to the object whose method or constructor is being called.
• Disambiguating field names from parameters
– Parameters and instance field names may clash. The this keyword explicitly refers to the instance.
• Calling other constructors
– When there are multiple constructors, they may call each other using this as if it were the method name.
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
Access Control
Access modifiers determine whether fields and methods may be accessed by other classes
• Toplevel:publicorpackage-private
• Memberlevel:public,protected,package-private,orprivate
no modifier
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
Class and Instance Members
The static keyword identifies class variables, class methods and constants.
• A class variable is common to all objects (there is only one version)
• A class method is invoked using a class name (not an object reference) and executes independently of any particular object.
• Aconstantcanbedeclaredbycombiningthefinalmodifierwith the static keyword.
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
Initializers
Fields may be initialized when they are declared. They can also be initialized by initializer blocks, which can initialize fields using arbitrarily complex code (error handling, loops, etc.).
• A static initializer block is consists of code enclosed by braces ‘{}’and preceded by the static keyword. It runs when the class is first accessed.
• A instance initializer block does not have the static keyword, and runs before the constructor body of the class.
Structured Programming 1110/1140/6710
Classes and Objects 2 O2
Enum Types
An enumerated type is defined with the enum keyword.
A variable of enum type must be one of a set of predefined values. This is useful for defining non-numerical sets such as NORTH, SOUTH, EAST, WEST, or HD, D, CR, P, N, etc.
• May have other fields
• Mayhavemethods
• Mayuseconstructors
• Can be used as argument to iterators
Structured Programming 1110/1140/6710
Interfaces
Structured Programming 1110/1140/6710
Interfaces O3
Interfaces
An interface can be thought of as a contract.
A class which implements an interface must provide the specified functionality. Compared to a class, an interface:
• Usesinterfacekeywordratherthanclass
• Cannotbeinstantiated(can’tbecreatedwithnew)
• Canonlycontainconstants,methodsignatures(notthebodies), nested types
– (Java 8+ allows default and static methods)
• Classesimplementinterfacesviaimplementskeyword
Structured Programming 1110/1140/6710
Interfaces O3
Interfaces as Types
An interface can be used as a type
• Avariabledeclaredwithaninterfacetypecanholdareferencetoa object of any class that implements that interface.
Structured Programming 1110/1140/6710
Inheritance 1
Inheritance Overriding and hiding Polymorphisim
The super keyword Introduction to Software Systems 1110/1140/1510/6710
Inheritance 1 O4
Inheritance
An inherited class is known as a subclass, derived class, or child class. Its parent is known as a superclass, base class, or parent class.
• Subclasses inherit via the extends keyword
• All classes implicitly inherit from java.lang.Object
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 1 O4
Overriding and Hiding Methods
• Instance methods
– If method has same signature as one in its superclass, it is said to override.
Mark with @Override annotation.
– Same name, number and type of parameters, and return type as overridden
parent method.
– The type of the instance determines the method
• Class methods
– If it has same signature, it hides the superclass method
– The class with respect to which the call is made determines the method
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 1 O4
Polymorphism
A reference variable may refer to an instance that has a more specific type than the variable.
The method that is called depends on the type of the instance, not the type of the reference variable.
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 1 O4
Hiding Fields
When a subclass uses a field name that is already used by a field in the superclass, the superclass’ field is hidden from the subclass.
Hiding fields is a bad idea, but you can do it.
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 1 O4
The super keyword
You can access overridden (or hidden) members of a superclass by
using the super keyword to explicitly refer to the superclass.
• A variable declared with an interface type can hold a reference to a
object of any class that implements that interface.
You can call superclass constructors by using super() passing arguments as necessary.
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 2
java.lang.Object
Final classes, methods and fields Abstract classes and methods
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 2 O5
Object as superclass
In Java all classes ultimately inherit from one root class: java.lang.Object. Implemented methods:
• clone() returns copy of object
• equals(Object obj) establishes equivalence
• finalize() called by GC before reclaiming
• getClass() returns runtime class of the object
• hashCode() returns a hash code for the object
• toString() returns string representation of object
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 2 O5
Final Classes and Methods
The final keyword in a class declaration states that the class may not be subclassed.
The final keyword in a method declaration states that the method may not be overridden.
Introduction to Software Systems 1110/1140/1510/6710
Inheritance 2 O5
Abstract Classes and Methods
The abstract keyword in a class declaration states that the class is abstract, and therefore cannot be instantiated (its subclasses may be, if they are not abstract).
The abstract keyword in a method declaration states that the method declaration is abstract; the implementation must be provided by a subclass.
Introduction to Software Systems 1110/1140/1510/6710
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com