Posts

ENCAPSULATION CHALLENGE

package com.cnc ; public class Main { public static void main ( String [] args) { Printer printer = new Printer( 50 , true ); System . out .println( "Initial Page count is " + printer .getNumberOfPages()); int pagesPrinted = printer .getNumberOfPages( 4 ); } } package com.cnc ; public class Printer { private int tonerLevel = 100 ; private int numberOfPages ; private boolean isDuplex ; public Printer ( int tonerLevel, boolean isDuplex) { if (tonerLevel>=- 1 && tonerLevel<= 100 ) { this . tonerLevel = tonerLevel; } else { this . tonerLevel =- 1 ; } this . isDuplex = isDuplex; this . numberOfPages = 0 ; } public int addToner ( int tonerAmount){ if (tonerAmount> 0 && tonerAmount<= 100 ){ if ( this . tonerLevel +tonerAmount > 100 ){ return - 1 ; } this . tonerLevel += tonerAmount

ENCAPSULATION

Consider an address: let's say it has a number and street name only Java  code for this could be : String number = "52" ; String street = "The Leeway" ;   System . out . println ( number + " " + street ); Ok so we see all the variables and the means to which the street was printed to us, if we  encapsulate  though we can do this: public class Address { private String streetName ; private String number ;   public Address ( String streetNametName , String number ){ this . streetName = streetNametName ; this . number = number ; }   public String getStreetName () { return streetName ; }   public void setStreetName ( String streetName ) { this . streetName = streetName ; }   public String getNumber () { return number ; }   public void setNumber ( String number ) { this . number = number ; }   public String fullDescrip

COMPOSITION

Image
  The composition  is an association that represents a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. It has a stronger relationship. Key Points It represents a part-of relationship. In composition, both the entities are dependent on each other. When there is a composition between two entities, the composed object cannot exist without the other entity. For example, if order HAS-A line-items, then an order is a whole and line items are parts If an order is deleted then all corresponding line items for that order should be deleted.  Favor Composition over Inheritance. Program Example of Java Composition Let us consider the following program that demonstrates the concept of composition. Step 1: First we create a class Bike in which we declare and define data members and methods: class Bike { // declaring data members and methods private String color; private int wheels; public void bikeFeatures() { System.out