Professional Documents
Culture Documents
w6 Java
w6 Java
w6 Java
~JAVA~
(CS13104)
2
Factory Method
• How to control construction of objects?
• The new operator considered harmful
• Factory Method lets a class defer instantiation
• Conditional object creation
• Or, defer instantiation to subclasses
• Defining a "virtual" constructor
3
Factory Method
public final class ComplexNumber {
public ComplexNumber(float aReal, float aImaginary) {
fReal = aReal;
fImaginary = aImaginary;
}
...
5
Back to OO properties
6
HAS-A Relationship
• Objects of one class can call the methods of another class
Car Engine
+ignite ()
7
HAS-A Relationship
• Typically this type of relationship exists between classes
• when a class is an attribute of another class.
public class Engine {
public boolean ignite () { public class Car {
... private Engine anEngine;
} private Lights headLights;
}
public class Lights { public start () {
private boolean isOn; anEngine.ignite ();
headLights.turnOn ();
public void turnOn () { }
isOn =true; }
}
} 8
Directed Association
• Unidirectional
• The association only goes in one direction.
• You can only navigate from one class to the other
• but not the other way around
9
Directed Association
• Bidirectional
• The association goes in both directions
• You can navigate from either class to the other
• Example,
public class Student {
private Lecture [] lectureList = new Lecture [5];
…
}
10
UML Representation
Car Light
• Unidirectional associations:
Gasoline Car
Student Lecture
• Bidirectional associations:
11
Inheritance
• Software reusability
12
Inheritance
• It involves
– Generalization
• Creation of general class that defines attributes
common to set of related classes
– Specialization
• Generalized class is inherited by other, specific classes,
each adding attributes unique to it
• Behaviors inherited from superclass
• Additional behaviors
• Class, that is inherited -> superclass (parent)
• Class, that inherits -> subclass (child)
13
SubClass
• Specialized version of superclass
• Inherits (almost) all of the instance variables
and methods defined in superclass
• Can add its own unique variables and
methods
14
“is-a” vs. “has-a”
• “is-a”
– Inheritance
– subclass object treated as superclass object
– Example: Car is a vehicle
• Vehicle properties/behaviors also car properties/behaviors
• “has-a”
– Composition
– Object contains one or more objects of other classes
as members
– Example: Car has a steering wheel
15
“is-a” vs. “has-a”
• Object of one class “is an” object of another class
– Example: Rectangle is quadrilateral.
• Class Rectangle inherits from class Quadrilateral
• Quadrilateral: superclass
• Rectangle: subclass
void printij()
{
System.out.println(i +" "+ j);
}
}
class B extends A {
// specialized features
}
17
Example
class A public class B extends A{
{ int z;
int x;
int y; B(){
A() { z = 10;
x=0; y=5; }
}
void display(){
void set(int p, int q){ Show();
x=p; y=q; System.out.println("Z="+z);
} }
}
void Show(){
System.out.println("X="+x+"\nY="+y);
}
}
18
The Test Class
public class Driver {
public static void main(String args[]) {
B x = new B();
x.Show();
x.set(8,9);
x.display();
}
}
OUTPUT:
X=0
Y=5
X=8
Y=9
Z=10
19
Multilevel Inheritance
• Hierarchy of inheritance
• As many inheritance levels as needed
• Example: classes A,B,C,D where D is a
subclass of C, which is a subclass of B, which is
a subclass of A
Each subclass
inherits attributes of
all of its superclasses
20
Multilevel Inheritance Example
class A{
…
}
class B extends A{
…
}
class C extends B{
…
}
class D extends C{
…
} 21
Multilevel Inheritance
• Class hierarchy
– Direct superclass
• Inherited explicitly (one level up hierarchy)
– Indirect superclass
• Inherited two or more levels up hierarchy
– Single inheritance
• Inherits from one superclass
– Multiple inheritance
• Inherits from multiple superclasses
22
Shape
TwoDimensionalShape ThreeDimensionalShape
23
Multiple Inheritance
• Subclass inherits attributes from more than 1
superclasses
• Java does not support multiple inheritance
through classes
• It is supported through Interface
24
Super/sub References
• Superclass references can refer to subclass
objects
– Super Ref -> Sub Obj (OK)
– Sub Ref -> Super Obj (Wrong)
• Type of the reference determines what members
can be accessed
• Super Ref -> Sub Obj
– Can access only the parts defined in superclass
– Reason: super class has no knowledge of subclass’s
added functionalities
25
See you next Day!
26
Super()
• To invoke the super class’s
– Constructor
– Method
– Variables
• Must be the first statement of the sub-class’s
Constructor
• Constructors are called in the order of
derivation
– From Super to Sub
27
Super()
• Super is the first statement during the class
– Hence, the order will be same whether or not
super is used
28
Other use of super
• To refer to super-class members
• General form:
– super.member
– <member> could be a method or a variable
– super.method() || super.variable
30
The Test Class
public class testing {
public static void main(String args[]) {
B x = new B();
x.Show();
x.set(8,9);
x.display();
}
}
OUTPUT:
inside A
inside B
X=0
Y=5
X=8
Y=9
Z=10 31
Another example
class A{
int x; public static void
int y; main(String [] args){
D obj = new D();
A() {
System.out.println("A constructor");
}
}
}
class B extends A{
B() {
System.out.println("B constructor");
}
}
class C extends B{
C() {
System.out.println("C constructor"); OUTPUT:
}
}
class D extends C{ A constructor
D() { B constructor
System.out.println("D constructor"); C constructor
} D constructor 32
}
Modification of constructor
• Defined
D() {
System.out.println("D constructor");
}
• Modified by compiler
D() {
super();
System.out.println("D constructor");
}
33
Modification of constructor
34
Modification of constructor
35
Overloading
• Like constructor overloading
• We can overload methods
– Should have different parameters
– may or may not have different return type
– Should have same name
– Should be in the same scope
36
Overriding
• Dynamic polymorphism
• Method in super-class re-defined in subclass
• Method should have Same Name and
Signature
• When called within subclass, it will always
refer to the overridden version defined in the
subclass
• Works only when name and signature are
exactly identical
37
Overriding
• Constructors can not be overridden or
inherited
38
Example
class A // Super class
{
void disp( )
{
System.out.println(“in class A”);
}
}
class B extends A //Sub class
{
void disp( )
{
System.out.println(“in class B”) // output
}
}
class Main
{
public static void main(String args[])
{
B b = new B();
b.disp();
}
39
}
Another Example
Output:
in Inh0 con
in Inh1 con
in Inh1
in Inh0 con
in Inh1 con
in Inh1
in Inh0 con 40
in Inh0
See you next Day!
41
More about Overriding
• Call to an overridden method is resolved at
run-time, rather than at compile-time
42
Dynamic Method Dispatch
• Call to an overridden method is resolved at
run-time
• Run-time polymorphism or late-binding
• Super class reference variable can store sub-
class objects class Main
{
public static void
main(String args[])
{
A obj = new B();
obj.disp();
}
} 43
Dynamic Method Dispatch
• When an overridden method is called through
a super class reference, Java determines which
version of that method to execute based upon
the type of the object being referred
44
Upcasting and Downcasting
•A subclass reference can be simply assigned to
superclass reference (not vice-versa)
•Upcasting is automatic.
•You need not use explicit typecast
45
Downcasting
• Casting the references of superclass type to
subclass type is called as downcasting
• Downcasting is not automatic
• Explicit typecast is required
• Compiler verifies that an inheritance relationship exists
between the source and destination reference types
46
Downcasting: Cases
•1
Cat c = new Cat();
Animal a = c;
•2
Animal a = new Animal();
Cat c = (cat) a;
47
•3
Animal a = new Cat();
Cat c = (cat) a;
•4
Cat c = new Cat();
Dog d = (dog) c;
48
Visibility
• Private and Public
class Person {
private String name;
private double height;
}
class Worker extends Person {
void print() {
System.out.println(“Worker” +
name+ “ ” + height);
}
}
Not Visible
49
Visibility
• Public
– Always Accessible
• Private
– Accessible within the class
• Protected
– Accessible within the class and its subclasses
50
Visibility
Private T
Protected T T
Public T T T
51
Access Modifiers
• Static
• Final
• Volatile
• Native (later)
• Transient (later)
• Abstract (later)
• Synchronized (later)
52
Static
• It is possible to create a member that can be
used without reference to a specific instance
• When declared as static, it can be accessed
before any objects of that class are created
• Both methods and variables can be declared
as static
• main () method is static because it is called
before any object exists
53
Static Variables
Static Variables -
• When objects of its class are declared, no copy
of static variables is made
• all instances of the class share the same static
variables
• All the static variables are initialized to their
default values
54
Example
public class Stuff {
public static String name = “This is a static variable";
}
56
Example
public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}
class MathUtility{
int result;
Error?
public static int add(int first, int second) {
result = first +second; return result;
}
}
57
Example
public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}
class MathUtility{
int result;
public static int add(int first, int second) {
result = first +second; return result;
}
}
58
Example
public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}
class MathUtility{
public static int add(int first, int second) {
return first + second;
}
}
59
See you next week!
60