Principles of OOP

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

Principles of OOP

Four main OOPs concepts in Java

• Inheritance : This is a special feature of Object Oriented Programming in Java. It lets


programmers create new classes that share some of the attributes of existing classes. This lets us build on
previous work without reinventing the wheel.

• Abstraction: Abstraction means using simple things to represent complexity. We all know how to
turn the TV on, but we don’t need to know how it works in order to enjoy it.

• Encapsulation: This is the practice of keeping fields within a class private, then providing access
to them via public methods. It’s a protective barrier that keeps the data and code safe within the class
itself. This way, we can re-use objects like code components or variables without allowing open access to
the data system-wide.

• Polymorphism : This Java OOPs concept lets programmers use the same word to mean
different things in different contexts. One form of polymorphism in Java is method overloading. That’s
when different meanings are implied by the code itself. The other form is method overriding.
1. Inheritance

• The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of parent class, and you can add new
methods and fields also.

• For Code Reusability.


Inheritance
• Inheritance is a fundamental Object Oriented concept superclass: Person
- name: String
• A class can be defined as a "subclass" of another class. - dob: Date
• The subclass inherits all data attributes of its superclass

• The subclass inherits all methods of its superclass


• The subclass inherits all associations of its superclass

subclass: Employee
• The subclass can: - employeeID: int
• Add new functionality - salary: int
• Use inherited functionality - startDate: Date
• Override inherited functionality
Inheritance
• When an object is created using new, the system must allocate
enough memory to hold all its instance variables.
• This includes any inherited instance variables

• In this example, we can say that an Employee "is a kind of" Person.
• An Employee object inherits all of the attributes, methods and
associations of Person

Person
- name: String Person
- dob: Date name = “abc"
dob = Jan 13, 1954
Employee
is a kind of name = “xyz"
Employee dob = Mar 15, 1968
- employeeID: int employeeID = 37518
- salary: int salary = 65000
- startDate: Date startDate = Dec 15,
2000
Inheritance Hierarchy
• Each Java class has one (and only one) superclass.
• C++ allows for multiple inheritance

• Inheritance creates a class hierarchy


• Classes higher in the hierarchy are more general and more
abstract
• Classes lower in the hierarchy are more specific and
There is no limit to the Class

concrete
number of subclasses a class
can have Class Class Class

• There is no limit to the depth


of the class tree. Class Class Class

Class
Accessing function
class ParentClass {

public void fun()


{
System.out.print("Hello word");
}
}
public class ChildClass {
public static void main(String args[]) {

ParentClass p = new ParentClass();


p.fun();
}
}
Using extends Keyword

package test;

class ParentClass {
int var=10;
}

public class ChildClass extends ParentClass {

public static void main(String args[]) {

ChildClass c = new ChildClass();


System.out.print(c.var);
}
}
Output :10
Using extends Keyword
class ParentClass {
public void fun()
{
System.out.print("Hello word");
}
}

public class ChildClass extends ParentClass{


public static void main(String args[]) {

ChildClass c = new ChildClass();


c.fun();
}
}

Output Hello world


Example

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;

public static void main(String args[]){


Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
– Programmer salary is:40000.0
– Bonus of programmer is:10000
Types of inheritance in java
Single Inheritance Example
class Animal{
void eat()
{System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output
barking...
eating...
Multilevel Inheritance Example

class Animal{ class BabyDog extends Dog{


void eat() void weep(){
{System.out.println("eating..."); System.out.println("weeping...");}
} }
} class TestInheritance2{
class Dog extends Animal{ public static void main(String args[]){
void bark(){ BabyDog d=new BabyDog();
System.out.println("barking...");} d.weep();
} d.bark();
d.eat();
}}
output
weeping...
barking...
eating...
Hierarchical Inheritance Example

class Animal{
void eat(){ class Cat extends Animal{
System.out.println("eating...");} void meow(){
} System.out.println("meowing...");}
class Dog extends Animal{ }
void bark(){ class TestInheritance3{
System.out.println("barking...");} public static void main(String args[]){
} Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//???
}}

meowing...
eating...
Super Keyword
Super Keyword

• super is a keyword.
• It is used inside a sub-class method definition to call a method defined in
the super class.
• The super keyword refers to the objects of immediate parent class.
• Private methods of the super-class cannot be called.
• Only public and protected methods can be called by the super keyword.
• It is also used by class constructors to invoke constructors of its parent
class.
• To access the data members of parent class when both parent and child
class have member with same name
• To access the method of parent class when child class has overridden that
method.
super keyword to access the variables of parent class

class Superclass
{
int num = 100;
}

class Subclass extends Superclass


{
int num = 110;

void printNumber(){
System.out.println(num);
}

public static void main(String args[]){


Subclass obj= new Subclass();
obj.printNumber();
}
}
• Output: 110
super keyword to access the variables of parent class

class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
super keyword to access the function of parent class

class ParentClass {

public void fun()


{
System.out.print("Parent Class :Hello word");
}

public class ChildClass extends ParentClass{

public void fun()


{
System.out.print("Child class :Hello world");
}

public static void main(String args[]) {

ChildClass c = new ChildClass();


c.fun();
}
}
Output: Child class :Hello world
super keyword to access the function of parent
class
class ParentClass {

public void fun()


{System.out.print("Parent Class :Hello world");}
}

public class ChildClass extends ParentClass{


public void fun()
{
super.fun();
System.out.print("Child class :Hello world");
}
public static void main(String args[]) {
ChildClass c = new ChildClass();
c.fun();
}}
Output:
Parent Class :Hello world
Child class :Hello world
super keyword to access the function of parent
class
class Grandparent{
public void fun() {
System.out.println("I am Grandparent");
}}

class ParentClass extends Grandparent {


public void fun() {
super.fun();
System.out.println("I am parent class ");
}}
public class ChildClass extends ParentClass{
public void fun(){
super.fun();
System.out.print("I am chid class");
}
public static void main(String args[]) {
ChildClass c = new ChildClass();
c.fun();
}}
Output
• I am Grandparent
• I am parent class
• I am child class
What if the child class is not overriding any method?

class Parentclass
{
void display(){
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void printMsg(){
display();
}
public static void main(String args[]){

Subclass obj= new Subclass();


obj.printMsg();
}
}

Output: Parent class method


No need of super
Constructor

class ParentClass {
ParentClass() {
System.out.println("Parent class constructor ");
}}

public class ChildClass extends ParentClass{


ChildClass(){
System.out.print("Child class constructor ");
}

public static void main(String args[]) {


ChildClass c = new ChildClass();
}}
Output:
• Parent class constructor
• Child class constructor
Encapsulation

• Encapsulation in java is a process of wrapping code


and data together into a single unit, for example
capsule i.e. mixed of several medicines.

• We can create a fully encapsulated class in java by


making all the data members of the class private.
Now we can use setter and getter methods to set
and get the data in it.

• The flexibility of a program is increased by making


the variables as write-only or read-only by omitting
the getter and setter methods.
Person

public class Person { public void setId(int id) {


this.id = id;
public int id; }
public String name;

public int getId() {


public void setName(String name) {
this.name = name;
return id;
} }

public String getName() {


return name; }
}
Student

public class Student extends Person {


public static void main(String[] args) {
Student student = new Student();
Scanner scanner = new Scanner(System.in);

System.out.print("Enter Student Name: ");


String name = scanner.nextLine();
student.setName(name);

System.out.print("Enter Student roll number: ");


int id = scanner.nextInt();
student.setId(id);

System.out.println("Student Name: " + student.getName());


System.out.println("Student Roll Number: " + student.getId());

}}
Teacher
public class Teacher extends Person {

public static void main(String[] args) {


Teacher t = new Teacher();
Scanner scanner = new Scanner(System.in);

System.out.print("Enter Teacher Name: ");


String name = scanner.nextLine();
t.setName(name);

System.out.print("Enter Teacher ID: ");


int id = scanner.nextInt();
t.setId(id);

System.out.println("Teacher Name: " + t.getName());


System.out.println("Teacher Id: " + t.getId());

}
Student

public class students extends Person {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int id;
String name;
students[] studentArray = new students[2];

for ( int i=0; i<studentArray.length; i++) {


studentArray[i]=new students();

System.out.print("Enter Id: ");


id = scanner.nextInt();
studentArray[i].setId(id);

scanner.nextLine();
Student

System.out.print("Enter Student Name: ");


name = scanner.nextLine();
studentArray[i].setName(name);

for ( int i=0; i<studentArray.length; i++) {

System.out.print("Student Id:"+studentArray[i].getId());
System.out.print("Student Name:"+studentArray[i].getName());
}}}
Access modifiers
Access modifiers

• Access modifiers are those which are applied before data members or methods of a class.
These are used to where to access and where not to access the data members or methods.

• Private : Visible to the class only (private).


• Public : Visible to the world
• Default (not a keyword) : Visible to the package.
• protected : Visible to the package and all subclasses .

• Note: Default is not a keyword (like public, private, protected are keyword)

• If we are not using private, protected and public keywords, then JVM is by default taking as
default access modifiers.
Person

public class Person { public void setId(int id) {


this.id = id;
private int id; }
private String name;

public int getId() {


public void setName(String name) {
this.name = name;
return id;
} }

public String getName() {


return name; }
}
Access modifiers (Public)

class testModifiers {
public int a=20;

public void show(){


System.out.println("Hello java");}
}

public class demoModifiers {


public static void main(String args[]) {
testModifiers obj=new testModifiers();
System.out.println(obj.a);
obj.show();
}
}

Output
• 20
• Hello java
Output ???

class testModifiers {
private int a=20;
private void show(){
System.out.println("Hello java");}
}

public class demoModifiers{


public static void main(String args[]) {
testModifiers obj=new testModifiers();
System.out.println("Value of a is:" + obj.a);
obj.show();
}
}
• Exception in thread "main" java.lang.Error: Unresolved compilation problems:
• The field testModifiers.a is not visible
• The method show() from the type testModifiers is not visible at
test.demoModifiers.main(demoModifiers.java:18)
Output ???

class demoModifiers{

private int a=20;

private void show(){


System.out.println("Hello java");}

public static void main(String args[])


{
demoModifiers obj=new demoModifiers();
System.out.println("Value of a"+obj.a);
obj.show();
}
}
Output :
• Value of a20
• Hello java
Access modifiers (Derived Class)
class testModifiers{
private int a=20;

private void show(){


System.out.println("Hello java");}

public void access(){


System.out.println(a);
show();}
}
public class demoModifiers extends testModifiers {
public static void main(String args[]) {
demoModifiers obj=new demoModifiers();
obj.access(); }
}
Output
• 20
• Hello java
Packages
Packages
Packages
Packages
Packages
Private With Extends
Private Without Extends
Protected With Extends
Protected Without Extends
Default with extends
Default without Extends
Tightly Encapsulated Class

• The tightly encapsulated class is a class whose every variable is declared private, whether
getter or setter methods are present or not or they are marked as public or not.
class P
{
int p =19;
//not tightly encapsulated class
}

class Q extends P
{
private int q=20;
//not tightly encapsulated class because it extends class P
}

class R extends Q
{
private int r=23;
//not tightly encapsulated class because it extends class Q
}
Final
Final

• This modifier is used to restrict the further modification of a variable or a method or a class.
The value of a variable which is declared as final can’t be modified once it gets a value. A final
method can not be overridden in the sub class and you can not create a sub class to a final
class.
Without Final Keyword

class testModifiers
{
int a=20;
}

public class demoModifiers extends testModifiers {


public static void main(String args[])
{
demoModifiers obj=new demoModifiers();
System.out.println(obj.a);
}
}
Output :
20
Without Final Keyword

class testModifiers
{
int a=20;
}

public class demoModifiers extends testModifiers {


public static void main(String args[])
{
demoModifiers obj=new demoModifiers();
obj.a=25;
System.out.println(obj.a);
}
}
Final Keyword with Variable

class testModifiers
{
final int a=20;
}

public class demoModifiers extends testModifiers {


public static void main(String args[])
{
demoModifiers obj=new demoModifiers();
obj.a=25; // Error

}
}
Final keyword with class

final class testModifiers


{
int a=20;
}

public class demoModifiers extends testModifiers { // Error


public static void main(String args[])
{
demoModifiers obj=new demoModifiers();
}
}
Without Final Keyword with Function

class ParentClass {
public void fun() {
System.out.println("Parent class fun ");
}}

public class ChildClass extends ParentClass{


public void fun() {
System.out.print("Child class fun");
}

public static void main(String args[]) {


ChildClass c = new ChildClass();
c.fun();
}}
Final Keyword with Function

class ParentClass {
final void fun() {
System.out.println("Parent class fun ");
}}

public class ChildClass extends ParentClass{


public void fun() { // error
System.out.print("Child class fun");
}

public static void main(String args[]) {


ChildClass c = new ChildClass();
c.fun();
}}
Collections
Grouping objects
Arraylist

• ArrayList is one of the List implementations built a top an array, which is able to dynamically
grow and shrink as you add/remove elements.

• Elements could be easily accessed by their indexes starting from zero.

• An ArrayList is an object that contains multiple arbitrary objects.

• To create an ArrayList, we can simply call the constructor from JAVA’s ArrayList class.

• Here is an example of creating an ArrayList and storing it in a variable so that we can use it:

– ArrayList myList;
– myList = new ArrayList();

• Or ArrayList can be created as

– ArrayList myList = new ArrayList();


Arraylist

• It is as if the ArrayList is a kind of “bag” into which we can place any objects.

• The ArrayList keeps the objects altogether so that we can pass the list around now as a single
object

• just like we can consider a “bag” to be asingle object, although it may contain many other
objects.
ArrayList vs. array

• Construction
– String[] names = new String[5];
– ArrayList<String> list = new ArrayList<String>();

• Storing a value
– names[0] = “x";
– list.add(“x");

• Retrieving a value
– String s = names[0];
– String s = list.get(0);
General format for an ArrayList
Raw ArrayList
• This is the general format for an ArrayList that can hold any kinds of objects.

• However, it is "highly recommended" that we specify the type of objects that will be stored in
the ArrayList.

• We do this by specifying the type between < > characters just before the round
brackets ( ) as follows:

• ArrayList<Object> myList = new ArrayList<Object>();


Type Parameters (Generics)

• ArrayList<Type> name = new ArrayList<Type>();

• When constructing an ArrayList, you must specify the type of elements it will
contain between < >.

• This is called a type parameter or a generic class.

• Allows the same ArrayList class to store lists of different types.

– ArrayList<String> names = new ArrayList<String>();


– names.add(“x");
– names.add(“y");
Raw type arraylist
i.e don't parameterize the arraylist
import java.util.ArrayList;
class ArrayListTestProgram {
public static void main(String args[]) {
ArrayList myList= new ArrayList();
myList.add("Hello");
myList.add(25);
myList.add(new Person());
myList.add(new Truck());
System.out.println(myList);
}
}
Student Arraylist Example
public class Student {

int roll_number, age;

String student_name;

public Student(int roll_number,String student_name,int age) {

this.roll_number = roll_number;

this.student_name = student_name;

this.age = age;
}
Student Arraylist Example
import java.util.*;

public class ArrayListDemo {

public static void main(String[] args) {

//Creating Student class objects


Student s1=new Student(1,“X",24);
Student s2=new Student(2,“Y",23);
Student s3=new Student(3,“Z",21);
Student s4= new Student(4,”w”,22)

ArrayList<Student> al=new ArrayList<Student>();

al.add(s1);
al.add(s2);
al.add(s3);

for(int i=0;i<al.size();i++) {

System.out.print(al.get(i).roll_number+" ");

System.out.print(al.get(i).student_name+" ");

System.out.println(al.get(i).age);

} }}

You might also like