Skip to main content

Posts

Showing posts from May, 2013

Composition in Java with code examples

Composition  "Have a " Relationship  OR  "Must have" relationship                    between two or more classes. Container class contains component's class object For example a  Car is composed of engine and body. Where Car is a container class and both Engine and Body are components class.  Life Time Issue in Composition Life time of component objects depends on container class If Container object destroyed, component objects will be also destroyed Car Example  There is a composition relationship between car's body and engine. Car must have Engine and body If Car destroyed, both Engine and Body will be destroyed class  Engine {   Engine  () {    System.out.println ( "Engine created" ) ; }   void  start () {    System.out.println ( "Engine Start" ) ;   } } class  Body {   Body  () { System.out.println ( "Body created" ) ; }   void  type () {    System.out.println ( "Sa

Life Time of Objects in Java with code Examples

Lifetime Concept in Java Programming Time between allocation and de-allocation of memory Life time depends on block i.e { }  life time starts when  declaration statement elaborated and expires at end of block   There is no delete keyword in java  Garbage collector is responsible for all deletes Java is free from dangling reference and garbage problem Why java does not support delete keyword? Java does not support delete keyword because there is a garbage collector in java This automatically runs and collects dangling or un-referenced objects.That is why there is no delete keyword in java like C++. Garbage collector can be explicitly like that System.gc();  When a life of object ends garbage collector runs automatically Example 1 { int a=5;// life Time start here a++; } //life time expire Example 2   Let Student is a class Student s;   // creating a reference of Student class    {Student t; // l      t= new Student(); // Life Time Start  

What are Objects In Java Programming

 Java Programming Objects   Object name in java is a reference  References are used to store address   All objects created in heap with new statement   There is no delete statement in java Deletion of object will be handled by garbage collector A special value null can be assigned Always passed by reference Object Example Let Student is a class Student t; // here t is a reference variable t=null;     // Assigning a reference to null  // t=NULL  Error here as  Java  is case sensitive null and NULL are different t = new Student(); // created in heap - Alias name can created for example Student y=t; // here y and t referring to same object in heap Parameter Passing  Primitives by value  Objects by reference Object as parameter  parameter passing by reference Example 1 class Car{ String make; String getMake() { return make;} void setMake(String m){make=m;} } class ChangeCarMake{  static void changeMake(Car p){   p.setMake("Suzuki");  } } class Test