Basic Concepts
Object Oriented Programming
Class
Collection of similar properties of object. Class is user defined data type which contains properties and methods
Object
Example/Instance of a class. It exist in real world.
How to create an object instance?
Syntax : new constructor_method
E.g. new Student()
Encapsulation
Binds together the data and functions & provide security
Achieved using POJO class (declare all variable as private & create public getter, setter methods)
Abstraction
Hide certain details and only show the essential features of the object.
Achieved using Interface & Abstract Class
Polymorphism
Poly - Many Forms. Same name can be used for different operations
Achieved using Method Overloading & Method Overriding.
Method Overloading & Overriding in Java
Overloading
Methods have same names but different number or type or order of parameters. Overloading is determined at the compile time. It's otherwise called static or compile time polymorphism
E.g.
display(String name)
display(String name, int number)
display(int number, String name)
Method won't be considered overloaded, if the return type is the only difference between two methods.
Overriding
A child class implements the method with same signature as a method in a parent class.
In method overriding both the super & sub class have same method signature, compile doesn't figure out which method to call at compile-time. In this case, JVM decides which method to call at runtime that's why it's called dynamic polymorphism.
Rule for overriding
Overridden Method (Super class method) | Overriding Method (Sub class method) |
---|---|
If public | should be public |
If protected | should be protected or public |
If default (no access specifier) | should be protected or public or default |
If private | can't be overridden |
If static | can't be overridden |
Covariant return type
Generally when we override a method, the signature has to be same for both methods. But there is a privilege to change the return type of the overriding method.
The return type we change should be the subtype of the return type of overridden method.
class Student {}class ScienceStudent extends Student { public Student getStudent() { return new Student(); }}class DoctorateStudent extends ScienceStudent { @Override public ScienceStudent getStudent() { return new Student(); }}
In above case, we are trying to override the getStudent()
method from ScienceStudent
class in DoctorateStudent
class. In order to override, the signature should of the methods has to same in both super and sub class.
In the above case, super class getStudent()
method returns Student
object. sub class getStudent()
method returns the ScienceStudent
object. Still it is a legal overriding. Its valid because ScienceStudent is sub class of Student object.
Abstract Class
Abstract class is class which may or may not contains abstract methods. The child extends Abstract class, it should give define the abstract methods.
Abstract Class can have
- Abstract methods and normal methods
- Static, final & normal variables
We cannot create object for abstract class
Interface
An interface is a reference type, similar to a class & it's used to achieve 100 % abstraction
Interface can have
- Only abstract methods, and by default all methods are public
- Only public static final variables //constants
- Cannot have static or final methods in interface
Class which extends Interface should give implementation for all methods in interface
If the class which extends interface is an abstract class, it need not give definition for all interface methods instead class which extends the abstract class has to define the undefined methods in interface
Marker Interface
An interface with no methods is called Marker Interface
E.g. Serializable, Clonnable are marker interfaces
These interfaces are used to indicate something to compiler or JVM that the class implementing any of these interface have some special behaviour
Inheritance
Inheriting the parent properties / behaviour. Represents the IS A relationship in real world. Achieved using extends keyword
Possible inheritance hierarchy
- One Interface can extend another interface
- One class can implements any number of interface
- One abstract class can implements any number of interface
Types of Inheritance
Single Inheritance
When a class extends another class
class A {
}
class B extends A {
}
Multilevel Inheritance
One class which inherits property of another class which itself inherited class from another super class is called Multilevel inheritance
class A {
}
class B extends A {
}
class C extends B {
}
Multiple Inheritance
Java doesnot support multiple inheritance directly. In general, multiple inheritance means one class extends property from more than one super class.
Why multiple inheritance not supported in Java?
When a class inherit from two or more classes, there is a chance two methods with same signature exist in both the super classes. So compiler will face ambiguity situation on choosing between the two method implementation. So in Java, multiple inheritance is not supported by default.
class A {
}
class B {
}
class C extends A,B {
// Error not possible
}
Super Class & Sub class reference
A Super class reference can hold both super class object & sub class Object
E.g.
class Animal {
}
class Monkey extends Animal {
}
class Human extends Monkey {
}
class Tiger extends Animal {
}
Animal a = new Animal() // Valid
Animal b = new Monkey() // Valid
Animal c = new Human() // Valid
Animal d = new Tiger() // Valid
Monkey m1 = new Monkey() // Valid
Monkey m2 = new Human() // Valid
Monkey m1 = new Animal() // Invalid
Human h1 = new Monkey() // Invalid
Tiger t = new Animal() // Invalid
So when we create a Sub class object, we can store it in Sub class reference as well as Super class reference as demonstrated in above examples
Advantages of above approach
Writing Generic method definitions is possible
E.g
Student
is the super class which contains the common functionality called calculateGPA()
.
public class Student {
String name;
int[] subjectMarks = new int[5];
Student(String name, int[] subjectMarks) {
this.name = name;
this.subjectMarks = subjectMarks;
}
void calculateGPA() {
int total = 0;
for (int i = 0; i < subjectMarks.length; i++) {
total = total + subjectMarks[i];
}
double average = total/5;
System.out.println("Your GPA is " + average);
}
}
ArtsStudent
, ScienceStudent
, EngineeringStudent
are subclasses of Student class
ArtsStudent
has one extra method - writeTheoryThesis()
which is not in parent class Student
class ArtsStudent extends Student {
ArtsStudent(String name, int[] subjectMarks) {
super(name, subjectMarks);
}
void writeTheoryThesis() {
System.out.println("Write theory thesis");
}
}
ScienceStudent
has one extra method - research()
which is not in parent class Student
class ScienceStudent extends Student {
ScienceStudent(String name, int[] subjectMarks) {
super(name, subjectMarks);
}
void research() {
System.out.println("Research & Learn");
}
}
EngineeringStudent
has one extra method - writeTechnicalThesis()
which is not in parent class Student
class EngineeringStudent extends Student {
EngineeringStudent(String name, int[] subjectMarks) {
super(name, subjectMarks);
}
void writeTechnicalThesis() {
System.out.println("Just go to college");
}
}
College
class has a method called prepareMarksheet()
which needs GPA to prepare the same. So it simply accepts Student as parameter
// Extract from College class
void prepareFinalMarkSheet(Student student) {
System.out.println("Student name is " + student.name);
student.calculateGPA();
}
Advantage here is, since the parameter is mentioned as Student
, we can pass ArtsStudent, ScienceStudent, EngineeringStudent
int[] artsMarksS1 = {89, 98, 100, 89, 75};
int[] artsMarksS2 = {98, 98, 100, 89, 75};
int[] artsMarksS3 = {67, 98, 100, 89, 75};
int[] artsMarksS4 = {47, 98, 100, 89, 75};
Student s1 = new ArtsStudent("Nithya", artsMarksS1);
Student s2 = new ScienceStudent("Paari", artsMarksS2);
Student s3 = new EngineeringStudent("Sri", artsMarksS3);
Student s4 = new EngineeringStudent("Gopika", artsMarksS4);
College college = new College();
college.prepareFinalMarkSheet(s1);
college.prepareFinalMarkSheet(s2);
college.prepareFinalMarkSheet(s3);
college.prepareFinalMarkSheet(s4);
Disadvantage is, when we store a Sub class object in Super class reference, we can't call the subclass specific methods anymore
E.g.
Student s1 = new ArtsStudent("Nithya", artsMarksS1);
s1.calculateGPA() // Valid
// s1.writeTheoryThesis() // Invalid because s1 is Student reference which can't call Arts Student method
How multiple inheritance indirectly achieved in Java?
In Java, multiple inheritance is indirectly implemented using Interface. So a class can implement more than one interface at time.
If two interfaces have methods with same s
Constructor
When you create a new instance of the class, Constructor will be called automatically.
This can be used to initialize values in the class
Restrictions
- Same name as Class Name
- Only one Default Constructor
- Constructor Overloading is possible
- When we use Parameterized Constructor, Default Constructor is mandatory
Understanding Signature of main() method
main
method is the default method called by the JVM (Java Virtual Machine)
when we execute our Program. Main method has to follow the below signature mandatorily
public static void main(String arg[]) {
}
syntax | meaning |
---|---|
public | Since the main method is called by JVM which is installed somewhere else in your machine |
static | Since JVM doesn't want to create Object for your class, to access main method, we mentioned static. So JVM can access main using class name itself |
void | Since the main method is called by the JVM , we don't want to return anything to JVM. Hence return type is void |
main | method name has to be main as mandated by the Java programming language |
String args[] | String array of parameters which a program can accept, we will discuss this in detail later |