Posts

Showing posts from May, 2023

Introducing Java Encapsulation Concept

Image
  Encapsulation Encapsulation  is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as  data hiding . To achieve encapsulation in Java − 1.) Declare the variables of a class as private. 2.) Provide public setter and getter methods to modify and view the variables values public class EncapTest { private String name ; private String idNum ; private int age ; public int getAge () { return age ; } public String getName () { return name ; } public String getIdNum () { return idNum ; } public void setAge ( int newAge ) { age = newAge ;

Introducing Java Interfaces Concept

Image
Interfaces Another way to achieve Abstraction  in Java, is with interfaces. Is equivalent to a Class. But not a class. interface FirstInterface { public void myMethod ( ) ; // interface method } interface SecondInterface { public void myOtherMethod ( ) ; // interface method } class DemoClass implements FirstInterface , SecondInterface { public void myMethod ( ) { System . out . println ( "Some text.." ) ; } public void myOtherMethod ( ) { System . out . println ( "Some other text..." ) ; } } class Main { public static void main ( String [ ] args ) { DemoClass myObj = new DemoClass ( ) ; myObj . myMethod ( ) ; myObj . myOtherMethod ( ) ; } } Like  abstract classes , interfaces  cannot  be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) Interface methods do not have a body - the body is provided by the &q