Object-Oriented Programming (OOP) in Java

Object-Oriented Programming (OOP) is central to Java language. Common terms that are used in OOP concepts are class, object, member, method, constructor, interitance, interface, abstract, public, private, and protected. The basic element of the OOP is class. A class is a template that can be used to create an object. Therefore, object is the instance of the class.


Creating a class


To create a class, you must use class keyword followed by the name of the class.

Example:
public class Student
{

}

In term of accessibility, a class can have three types of members-private, public, and protected members. Private member can’t be accessed by the code outside the class. In contrast, public member is accessible to the outside environment of the class. To declare a private member, you can use private keyword and to declare a public member, you can use public keyword. A protected member is accessible only within the class that defines and the derived class. You use the protected keyword to define a protected member. You will see an example of using the protected keyword in the Class Inheritance section later in this tutorial.

Example:
public class Student
{
 private int stnumber;
 private String stname;
 private String stsex;


}
 

A member of class can be variable or method. A variable is a member that will be used to store data. All members defined in the Student class above are variables. In contrast, a method member is called to perform action on the data.

Methods


A method is a member of a class that can be called to perform a specific task. Before you can call it, you must define it in the class. In the example below, there are six methods defined in the Student class: setNumber, setName, setSex, getNumber, getName, and getSex. The first three methods will be invoked to set number, name, and sex of a student. The last three methods can be called to get the number, name, and sex.

Example:
public class Student
{
  private int stnumber;
  private String stname;
  private String stsex;
  public void setSumber(int n){
     stnumber=n;
}
 public void setName(String name){
   stname=name;
}
 public void setSex(String se){
   stsex=se;
}
 public int getNumber(){
   return stnumber;
}
 public String getName(){
    return stname;
}
 
 public String getSex(){
    return stsex;
   }

}

Creating objects from a class


To access members of the class, you must create its object. The object can be created by using the new keyword.
Example:
Student stu=new Student();

Accessing a class’s public members through objects


To access public members of a class, you must write its object’s name followed by dot sign(.) and the names of its members.


Example:
class Student
{
  private int stnumber;
  private String stname;
  private String stsex;
  public void setNumber(int n){
    stnumber=n;
  }
 public void setName(String name){
   stname=name;
 }
 public void setSex(String se){
   stsex=se;
 }
 public int getNumber(){
   return stnumber;
 }
 public String getName(){
   return stname;
}
 public String getSex(){
  return stsex;
   }
}
public class myclass{
 public static void main(String[] args){
   Student s=new Student();//object was created.
   s.setNumber(100); //The members of class were accessed.
   s.setName("Dara");
   s.setSex("M");
   System.out.print("id="+s.getNumber()+"  name="+s.getName()+"      sex="+s.getSex());
}
}


Class Constructors


Constructor is a special method that can be used to initialize objects of the class when they are created. The constructor is declared with only the name of the class followed by brackets.


Example:
class Student
{
  private int stnumber;
  private String stname;
  private String stsex;
  Student(){
   stnumber=001;
   stname="Piseth";
   stsex="M";
}
public void setNumber(int n){
  stnumber=n;
}
public void setName(String name){
   stname=name;
}
 
public void setSex(String se){
   stsex=se;
}
public int getNumber(){
   return stnumber;
}
public String getName(){
   return stname;
}
public String getSex(){
   return stsex;
   }
 
}
public class myclass{
 public static void main(String[] args){
    Student s=new Student();
    System.out.print("id="+s.getNumber()+" name="+s.getName()+"    sex="+s.getSex());
    s.setNumber(100);
    s.setName("Dara");
    s.setSex("M");
    System.out.print("id="+s.getNumber()+" name="+s.getName()+" sex="+s.getSex());
   }
}

You also can pass parameters through constructor.
Example:
class Student
{
  private int stnumber;
  private String stname;
  private String stsex;
  Student(int n, String name, String sex){
     stnumber=n;
     stname=name;
     stsex=sex;
}
public void setNumber(int n){
    stnumber=n;
}
public void setName(String name){
    stname=name;
}
public void setSex(String se){
   stsex=se;
}
public int getNumber(){
   return stnumber;
}
public String getName(){
   return stname;
}
public String getSex(){
   return stsex;
   }
}
public class myclass{
  public static void main(String[] args){
    Student s=new Student(002, "Channa","M");
    System.out.print("id="+s.getNumber()+" name="+s.getName()+" sex="+s.getSex());
    s.setNumber(100);
    s.setName("Dara");
    s.setSex("M");
    System.out.print("id="+s.getNumber()+" name="+s.getName()+" sex="+s.getSex());
   }
}


Class inheritance


Inheritance enables a derived class or a child class to inherit variables and methods from a base class or super class. The derived class can also add new members or override the existing members of its base class. For example, a company sells two types of products, shoe and shirt. Each shoe and shirt have the following common pieces of information:

-ID

-Name

-Decription

-Branch name

-Color

-Gender

-Size

-Price

-Available items in stock

However, shoe and shirt products have their unique pieces of information. A shoe contains one additional field: shoe type. A shirt contains two additional fields: sleeve type and material.

In this snenario, there are three classes that will be created. One class is Product class that contains the common pieces of information. Two other classes are Shoe and Shirt. The two classes will inherit the common fields from its super class (Product) . In the Shoe class, there is only one variable that has to be defined (ShoeType). In the Shirt class, you need to define two variables: SleeveType and Material. In the Product class, the printProduct method is defined to print the common pieces of information. This method will be overridden by the Shoe and Shirt class so that it can print additional data. In Java, you must use the extends keyword to do inheritance of classes.

import java.util.ArrayList;

class Product{
protected String ProID;
protected String ProName;
protected String ProDescription;
protected String ProBrand;
protected String ProColor;
protected String Gender;
protected String ProSize;
protected float ProPrice;
protected int availableItems;

Product(String id, String name, String des, String brand, String color, String gender, String size, float price, int numItems){

ProID=id;
ProName=name;
ProDescription=des;
ProBrand=brand;
ProColor=color;
Gender=gender;
ProSize=size;
ProPrice=price;
availableItems=numItems;
}


protected void printProduct(){

System.out.println("\tID:"+ProID);
System.out.println("\tName:"+ProName);
System.out.println("\tDescription:"+ProDescription);
System.out.println("\tBrad:"+ProBrand);
System.out.println("\tColor:"+ProColor);
System.out.println("\tGender:"+Gender);
System.out.println("\tSize:"+ProSize);
System.out.println("\tPrice:"+ProPrice);
}

}
class Shoe extends Product{

private String ShoeType;
Shoe(String type, String id, String name, String des, String brand, String color, String gender, String size, float price, int numItems){
  super(id,name,des,brand,color,gender, size, price, numItems);
  ShoeType=type;
}

public void printProduct(){
  super.printProduct();
  System.out.println("\tShoe Type:"+ShoeType);

}

}
class Shirt extends Product{

private String SleeveType;
private String Material;
Shirt(String type, String material, String id, String name, String des, String brand, String color, String gender, String size, float price, int numItems){
  super(id,name,des,brand,color,gender, size, price, numItems);
  SleeveType=type;
  Material=material;
}

public void printProduct(){
  super.printProduct();
  System.out.println("\tSleeve Type:"+SleeveType);
  System.out.println("\tMaterial:"+Material);
}

}
public class InheritanceDemo {


private static ArrayList<Product> products;
public static void main(String[] args){

products=new ArrayList<Product>();
addProduct(new Shoe("dress","1","comfortable shoe","This is a comfortable shoe from USA","Adidas","red","female","30",100.0f,200));
addProduct(new Shirt("dell","fabrics","2","bird","This is a T-shirt from USA","Hendrix","White","male","m",50.0f,300));
listProducts();

}

public static void addProduct(Product p){
  products.add(p);
}

public static void listProducts(){
  for(Product p:products){
    p.printProduct();
    System.out.println("--------------------------------");
      }
    }
}


Inheritance in Java


Abstract Class


An abstract class is created for the purpose of being inherited. We cannot create objects from the abstract class. A member of an abstract class can be private, public, and protected. You can define a method member that must be overridden in its sub-class by using the abstract keyword. The method that is declared with the abtract keyword has no body. Its body must be implemented in the sub-class.


abstract class Cls
{
   public int sum(int a,int b){return 0;};

//The subtract method must be overridden by a sub-class

   abstract int subtract(int a,int b);
}

//implementing the abstract class

public class Calc extends Cls{

  public static void main(String ars[]){

    Calc cal=new Calc();

    int result=cal.sum(10,20);

   System.out.println("Result:"+result);

   }

//overriding the sum() method

  public int sum(int a,int b){

    return(a+b);

  }

//overriding the subtract() method

  public int subtract(int a,int b){

    return(a-b);

  }

}


Interfaces


An interface can be used as a template for other classes. Its purpose is to be inherited. It sounds like an abstract class. However, in the interface, you cannot declare variables unless they are constants. In addition, methods can be declared, but those are without bodies. You can implement the interface by using "implements" keyword.
Example:
interface Inter
{
 public void print();
}

public class Print implements Inter{
  public static void main(String args[]){
  Print bs=new Print();
  bs.print();
}

public void print(){
   System.out.println("Implementing interface example");
}

}


HTML Comment Box is loading comments...



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.