PACKAGES AND INTERFACES Byju Veedu Packages Packages are
PACKAGES AND INTERFACES Byju Veedu
Packages • Packages are containers , used to keep the class namespace compartmentalized. • The package declaration in a java file can only be preceded by white spaces or comments • Only one package declaration is permitted. • Packages are stored in hierarchical manner and are explicitly imported into new class definitions. •
Interface • Abstract a class’s interfaces from their implementations • Pure abstract classes with no implementation • Only methods and constant declaration are allowed. • Once defined any number of classes can implement an interface • A class can implement any number of interfaces.
Interface example public interface Bounceable { double pi=3. 14; void bounce(); void set. Bounce. Factor(int factor); } class Tire implements Bounceable{ private int bounce. Factor; public void bounce() { System. out. println("Bouncing with factor : "+bounce. Factor); } public void set. Bounce. Factor(int factor) { this. bounce. Factor=factor; } }
Abstract class • A class with at least one abstract method should be declared as abstract • An abstract class can never be instantiated. • Methods marked abstract ends in semicolon rather than curly braces • A class which extends an abstract class should either implement all the abstract methods or should be declared abstract.
Abstract class example abstract class Fruit { abstract String get. Color(); abstract double get. Price(); } public class Apple extends Fruit{ String get. Color() { // TODO Auto-generated method stub return "Red"; } double get. Price() { // TODO Auto-generated method stub return 40; } }
Cloneable • It is a marker interface , that is an interface without any methods • A class implements cloneable to indicate to the object. clone() method that it is legal for the clone method to make a copy of the object
final • A final class cannot be subclassed • A final variable’s value cannot be changed one initialized. • A final method cannot be overridden.
Hands-on • Creating and implementing an interface • Implementing multiple interfaces • Create and extend an abstract class • Cloning a object • Use of final
- Slides: 9