EE3206 Java Programming and Applications: Lecture 4. Object-Oriented Programming (Classes, Objects, Inheritance)
EE3206 Java Programming and Applications: Lecture 4. Object-Oriented Programming (Classes, Objects, Inheritance)
• Object: Any entity that has state (what it knows) & behavior (what it can do) is an object.
• Ex: a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
• An Object can be defined as an instance of a class.
• An object contains an address and takes up memory.
• Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response
returned by the objects.
• Ex: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Objects
• An object has a unique identity, state, and behavior.
• The identity is the name of an object.
• Student peter = new Student();
• Advantage of Method
• Code Reusability
• Code Optimization
• For a simple method like calculateScore, we just use the name of the method, where we
want it to be executed, followed by parentheses, and a semi-colon to complete the
statement, as follows
Method Syntax -2 (have Input, No return)
• This method has a name, takes input parameters, and returns no data from the method
(which is what void means in this declaration).
• To execute a method that's defined with parameters, you have to pass variables, values,
or expressions that match the type, order and number of the parameters declared.
Method Syntax -3 (have Input parameters and return)
• Similar to declaring a variable with a type, we can declare a method to have a return type.
• This declared type is placed just before the method name.
• Return statement is required in the code block, which returns the result from the method.
Method Declaration
• Method Declaration is composed of two things
1. Declaring Modifiers; These are keywords with special meanings, such as public and
static as examples, but there are others.
2. Declaring the return type;
• void is a Java keyword meaning no data is returned from a method.
• Alternatively, the return type can be any primitive data type or class.
• If a return type is defined, the code block must use at least one return statement,
returning a value, of the declared type or comparable type.
Method Declaration
• Naming Conventions for method; Lower camel case is recommended for method.
• If a method declares a return type, then a return type is required at any exit point from the
method block.
Return Statement for methods with a return type
• If you have a nested code block in a method, all possible code segments must result in a
value being returned.
Return Statement for methods with a return type
• Better method is to declare a default return value at the start of a method, only have a
single return statement from a method, and returning that variable.
Return Statement for methods with void return type
• In this case, the return statement is optional, but it may be used to terminate execution of
the method, at some earlier point than the end of the method block.
Examples
import java.util.Scanner;
public class Methods {
public class EvenOdd {
public static void main(String[] args) { public static void main (String args[]) {
addition(10, 12);
public static void findEvenOdd(int num){ //user defined method
} if(num%2==0)
System.out.println(num+" is even");
public static void addition(int a, int b) { else
System.out.println(a + b);
System.out.println(num+" is odd");
}
}
public static void multiply(int a, int b) { }
System.out.println(a * b);
}
}
Examples
public class Main { public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Welcome"); // Create a checkAge() method with an integer variable called age
} static void checkAge(int age) {
public static void main(String[] args) { // If age is less than 18, print "access denied"
myMethod("Liam"); if (age < 18) {
myMethod("Jenny"); System.out.println("Access denied - You are not old enough!");
myMethod("Anja");
} // If age is greater than, or equal to, 18, print "access granted"
} } else {
System.out.println("Access granted - You are old enough!");
public class Main { }
class <class_name>{
field;
method;
}
• Instance variable
• A variable which is created inside the class but outside the method.
• Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created.
Object and Class
• Creating the object
• new keyword: We create the object of a particular class by new keyword and save
the object memory address into a reference variable.
• The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
• We can create objects within a class (Example A) or outside the class (Example B)
Example A. Object Creation within the class
//How to define a class and fields
class Student{ // First, define a Student class.
// Next, define fields. Here, we have instance variables.
int id; //field or data member or instance variable
String name;
public static void main(String args[]){ //We are creating main method inside the Student class
//We are creating an object or instance of Student
Student s1=new Student(); //by using new keyword
• we created a Student class with two data members id and name by using new keyword.
Example B. Object Creation outside the class
//Have the main method in another class
class Student{ //Student class creation
int id;
String name;
}
//Creating another class TestStudent1 that contains the main method
class TestStudent1{
• We can have multiple classes in different Java files or single Java file.
Stack and Heap Memory in Java
• Stack
• Memory structure managed in a LIFO (Last In, First Out) method
• Stack memory is very fast (fast access, allocation, deallocation), but has short life
• It is not bound by the same rules as the stack, i.e., can store a large amount of data.
• Heap memory size is greater than Stack, but requires huge overhead.
HEAP
Reference Variable
• Reference variable
• Variable that holds the memory address of an object rather than the actual object
itself.
• Reference variables are declared with a specific type, which determines the methods
and fields that can be accessed through that variable.
• When an object is created using the new keyword, memory is allocated on the heap
to store the object's data. The reference variable is then used to refer to this memory
location, making it possible to access and manipulate the object's properties and
behaviors.
Example. Initializing the Object through a reference variable
• Initializing an object means storing data into the object.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
//storing data into ‘id’ and ‘name’
s1.id=101; //using reference variable ‘s1’.
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
}
}
Example. Initializing Multiple Objects
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
Student s1=new Student(); //Creating multiple objects s1, s2
Student s2=new Student();
//Printing data
System.out.println(s1.id+" "+s1.name); System.out.println(s2.id+" "+s2.name);
}
}
Example. Initializing the Object through method
• We have two methods inside the Student Class; insertRecord() and displayInformation()
class Student{
int rollno;
String name;
class TestStudent4{
public static void main(String args[]){
// We initialized the Objects by using insertRecord() method.
Student s1=new Student(); Student s2=new Student();
s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan");
// We displayed the data of the Objects by using displayInformation() method.
s1.displayInformation(); s2.displayInformation();
}
}
Example. Calculating the area of Rectangle
class Rectangle{
int length; int width;
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle(); Rectangle r2=new Rectangle();
r1.insert(11,5); r2.insert(3,15);
r1.calculateArea(); r2.calculateArea();
}
}
Creating Multiple Objects by One Type Only
• We can create multiple objects by one type only as we do in case of primitives.
• User-defined Method
• method written by the user or programmer
• A method that belongs to a class rather than an instance of a class is a static method.
int s;
• We can apply static keyword with variables, methods, blocks and nested classes.
• Static variables are class-level variables that are shared among all objects of a class,
such as the number of instances of a class that have been created.
• Instance variables are used to represent object-level data and are used to store data that
is unique to each objects. They can be accessed and modified using object references.
Example of Static Variable
int result=Calculate.cube(5);
System.out.println(result);
}
}
Example of Static Variable
class Example {
static int count = 0;
• The value of the static variable remains the same across all the objects.
Example of Static Variable
class Circle {
static double pi = 3.14; //Static Variable
double radius;
class TestOverloading{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
System.out.println(Adder.add(11,11,11));
}
}
Constructor
• Constructor is a code block that is called when an instance of the class (object) is created.
• When we call a constructor, memory for the object is allocated in the Heap memory.
Default Constructor
(no-arg constructor)
Java Constructor
Parameterized
constructor
Constructor
• Default Constructor
• A constructor is called "Default Constructor" when it doesn't have any parameter.
//main method
public static void main(String args[]){
Bike1 b=new Bike1(); //calling a default constructor
}
• Default constructor provides the default values to the object like 0, null, for a given type.
Constructor
• Parameterized Constructor
• A constructor which has a specific number of parameters is called a parameterized
constructor.
• Constructor overloading; we can have more than one constructor with different
parameter lists, so that each constructor performs a different task.
Example of Parameterized Constructors
class Student4{
int id; String name;
public static void main(String args[]){ //creating objects and passing values
Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display(); s2.display();
}
Example of Constructor Overloading
class Student5{
int id; String name; int age;
//creating two arg constructor
Student5(int i,String n){
id = i; name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i; name = n; age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
• Constructors cannot be invoked directly as a normal method. They are invoked using the
new operator when an object is created.
• new ClassName();
• new Student(); // correct
• Student.Student(); // wrong
• peter.Student(); // wrong
• Constructors play the role of initializing objects. You should place your code of
initialization inside a constructor.
• new Circle(); // without args
• new Circle(5.0); // with args
This Keyword
• The keyword this is a reference to the current object context (i.e. the executing object).
• We can not use this keyword in a static context, e.g., static method, static variable, static
class
Example on This Keyword
class Student{
int rollno; String name; float fee;
Student(int rollno,String name,float fee){ //Prob. The parameters and instance variables
rollno=rollno; name=name; fee=fee; //are the same, which causes confusion
}
void display(){ System.out.println(rollno+" "+name+" "+fee); }
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display(); s2.display(); }
}
• What is the problem? Find the problem and resolve it by using ‘This’ keyword.
Organizing Classes
• Classes can be organized into logical groupings, which are called
packages (which is similar concept to a folder in a computer)
• You declare a package name in the class using the package statement.
• If you don't declare a package, the class implicitly belongs to the default
package.
Access modifiers for the class
• What is the problem? Find the problem and resolve it by using different access modifier.
Example
//save in A.java file within package1
package package1;
public class A{
public void msg(){ System.out.println("Hello"); } //Public
}
package package2;
import package1.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Getter vs. Setter
• A getter is a method on a class, that retrieves the value of a private field, and returns it.
• A setter is a method on a class, that sets the value of a private field.
• The purpose of these methods is to control, and protect, access to private fields.
• It is a good practice to use private variables in class.
• Syntax
class ABC{
private variable;
• Inheritance;
• Super v.s. this keyword
• Polymorphism
• Method Signature -> Overloading vs Overridding
[1] OOP - Inheritance
• In Java, one class (A) can inherit all the members (i.e. data
fields and methods) from another class (B)
• Terminologies
• Class: A group of objects with common properties. It is a template or
blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
• Reusability: reusability is a mechanism to reuse the fields and methods
of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
[1] OOP - Inheritance
• Use the keyword extends
class SmartPhone extends Phone { … }
• In the previous example, SmartPhone inherits everything (only non-private) from Phone.
String Texture = "Matte"; static boolean connection = true; // public static void leftClick() {
// System.out.println("left clicked!");
// public static void leftClick() { // public static void leftClick() { // }
// System.out.println("left clicked!"); // System.out.println("left clicked!"); //
// } // } // public static void rightClick() {
// // // System.out.println("right clicked!");
// public static void rightClick() { // public static void rightClick() { // }
// System.out.println("right clicked!"); // System.out.println("right clicked!");
// } // } public static void
highResolutionSensing() {
public static void setColor(String color) { public static void connect() { System.out.println("Ultra accurate
System.out.println(color); if (connection) { Mode!");
} System.out.println("connected"); }
} }
} }
}
Examples of Inheritance
• Mouse.java file • Main.java file
• Similar to the keyword this, the keyword super can also be used to refer to a member
(method or data field) of the superclass:
• super.methodName();
• super.name = “Peter”;
Examples of Super Keyword
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Examples of Super Keywords
class Animal{
void eat(){ System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){ System.out.println("eating bread...");}
void bark(){ System.out.println("barking...");}
void work(){
super.eat();
bark(); }
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Examples of Super Keyword
class Animal{
Animal(){ System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super(); // super keyword can invoke the parent class constructor
System.out.println("dog is created");
}}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Difference between This and Super keyword
• The keyword super is used to access or call the parent class members (variables and
methods).
• The keyword this is used to call the current class members (variables and methods).
• this is required, when we have a parameter with the same name, as an instance
variable or field.
• This() is used to call a constructor, from another overloaded constructor in the same
class.
• this() and Super() call must be the first statement in a constructor. Otherwise, it causes
compile error.
Constructors Bad Example
• Every class inherits methods from Object class. There are a few useful methods provided
by this class:
• toString() - return a string representation of the object.
• hashCode() - return a hash code that uniquely identifies the object
• equals(Object obj) - indicates whether some other object is "equal to" this one
Circle c = new Circle();
System.out.println(c.toString()); // Circle@15037e5
Polymorphism
• Polymorphism is the ability of an object to take on many forms. This allows us to perform
a single action in different ways.
• Polymorphism allows you to define one interface and have multiple implementations.
• Method Overriding: process when the subclass or a child class has the same
method as declared in the parent class.
Examples of Polymorphism
• The Parent-class Animal and child-class Pig,
Dog have their own implementation of an
animal sound.