Showing posts with label Applied Java Tutorials. Show all posts
Showing posts with label Applied Java Tutorials. Show all posts

Monday, August 13, 2012

Core Reusability

Code Reusability
Code reusability means reusing the existing classes.
In java code reusability is achieved by using two concepts:
1)      Composition
2)      Inheritance
Composition:
Composition means creating object of existing class as data member of new class.
it is a has-a relationship.
example: Student has a class room, library has books and Student has a library.
Composition is achevied by in 2 techniques:
1. Association:
Here association is defined as a Sudent connot exist without ClassRoom, means you cannot create a student object without creating ClassRoom class Object.
class Student{
ClassRoom croom; //here croom object must created.
}
we seen one-to-one, one-to-many,many-many,many-one are the associations relationships in java.
2. Aggregation:
Aggregation is also has-a relationship, but here the relationship is organized is loosely.
example: the relationship b/w the Library and Student. Here a Library Object is created with out creating the Student object.
class Library{
Student stu;// it is not mandatory to exist stu objecgt.
}

//existing class defined by user1
Point.java
Package pack1;
public class Point{
public int x;
public int y;
}
Javac –d . Point.java
Note:move Point.java to pack1.
//new class defined by user2
Package pack2;
Import pack1.Point;
public  class Circle {
public int radius;
public Point center=new Point();
}
Javac  -d . Circle.java
Note: move Circle.java to pack2;
Demo.java
public class Demo {
public static void main(String[] args) {
Circle c=new Circle();
c.radius=3;
c.center.x=1;
c.center.y=2;
System.out.println(c.radious);
System.out.println(c.center.x);
System.out.println(c.center.y);
}
}