Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
if (obj.getClass().isInstance(Statement.class)) {
doStuffWithStatements((Statement) obj));
}
if (obj instanceof C) {
//your code
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Sample {
public static void m1(int i) {
System.out.println("Int arg");
}
public static void m1(float f) {
System.out.println("Float arg");
}
public static void main(String [] args) {
Sample s1 = new Sample();
s1.m1(10); // Int-arg
s1.m1(10L); //Float arg
s1.m1(10.5f); //Float arg
s1.m1(10.5); // compiler error "Cannot find symbol"
}
}
As you can see in above example, when we pass null in m1() String version
method got executed, since the child class methods gets more priority.
Nows lets take another example
1 class Test
2 {
public void m1(StringBuffer sb)
3
{
4
System.out.println("String Buffer");
5
}
6
7
public void m1(String s)
8
{
9
System.out.println("String here");
10
}
11
12
public static void main(String[] args)
13
{
14
Test t = new Test();
15
t.m1("Harsha"); // String version
16
t.m1(new StringBuffer("Harsha")); //StringBuffer Version
17
t.m1(null); // Compiler Error - reference to null is ambigious
18
}
19 }
20
As we can notice, in the above example we will get compile time error when we
try to pass null since both String and StringBuffer are subclasses of object.
3. In overloading method resolution is always taken care by compiler
based on reference type. Runtime object wont play any role.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Animal
{
}
class Monkey extends Animal
{
}
class Test
{
public void m1(Animal a)
{
System.out.println("Animal version");
}
public void m1(Monkey m)
{
System.out.println("Monkey version");
}
public static void main(String[] args)
{
Test t = new Test();
Animal a = new Animal();
t.m1(a); //Animal Version
Monkey m = new Monkey();
t.m1(m); //Monkey version
a = new Monkey();
t.m1(a); // Animal version
}
}
In last method even when we pass a Monkey object the output is Animal
version since the reference type is of Animal and compiler only cares about
reference type.
In overriding method names and argument types must be matched i.e., method
signatures must be same.
Final methods cannot be overridden. Final Classes cannot be inherited. Abstract classes
cannot be instantiated. Abstract methods must be overridden. If a method is abstract
then its class must be abstract. But if a class is abstract all its methods need not be
abstract.
Attributes are like object variables. Operations are not methods but high level
operational functions.
Multiplicity is 0..1, 1, *, 0..*, 1..*.
Single line Association
Single line with hollow diamond Aggregation
Single line with filled diamond Composition