Java Basics (Fundamentals)
Java Basics (Fundamentals)
(Fundamentals)
By
Mahesh Kumar G P
Agenda
Java Ws…?
Parameter passing
Packages
Encapsulation
Getter methods returning objects
Assignments
Java Ws
Y(20)
X(10)
B(20)
A(10)
Parameter passing
20
X
B
10
A
Parameter passing
“pass by value”
Packages: WHY?
ease of maintainence
Encapsulation
Enforcing constraints
Hiding implementation
Synchronization
Encapsulation ? reference leaking
}
Encapsulation ? reference leaking
Returning references to
private/protected
mutable
objects
How to rectify?
cloning!
What is inheritance
Person
Employee Student
What is inheritance
data
methods
or both
from another class
it is inheritance
Why inheritance
Code reuse
Less code to maintain
Creation of frameworks
parent classes perform common tasks
children classes provide specific details
Loose coupling/pluggability
Polymorphism
Polymorphism
poly: many
morph: form
when a class reference takes many forms
class Parent...
class Child1 extends Parent...
class Child2 extends Parent...
Parent p = new Child1(); //or Child2() or Parent()
Method overriding: dynamic
polymorphism
public class Foo
{
public void foo(){S.O.P.(?in parent foo()?);}
}
class Foo
{
public void foo()...
}
class Foo
{
protected void foo()...
}
class Foo
{
protected int x = 10;
public void foo(){S.O.P.(x)}
}
class FooChild extends Foo
{
protected int x = 20;
}
class Foo
{
public static void foo(){S.O.P.(?in parent?)}
}
class FooChild extends Foo
{
public static void foo(){S.O.P.(?in child?)}
}
“in parent”
class Foo
{
public static void foo(){S.O.P.(“in parent”)}
}
class FooChild extends Foo
{
public static void foo(){S.O.P.(“in child”)}
}
class Foo
{
protected static int x = 10;
public static void printX(){S.O.P.(x);}
}
class FooChild extends Foo
{
public static void setX(int val){x = val;}
}
FooChild.setX(100);
Foo.printX(); // what will this print?
Static member inheritance
e.method(23);
e.method("Hello"); // Error. Even though instance has method.
}
}