[go: up one dir, main page]

0% found this document useful (0 votes)
40 views89 pages

EE3206 Java Programming and Applications: Lecture 4. Object-Oriented Programming (Classes, Objects, Inheritance)

This document discusses object-oriented programming concepts including classes, objects, methods, and inheritance. It begins by explaining that classes are templates used to create objects which have both state (data fields) and behavior (methods). Methods are functions that can be called on objects and can accept parameters and return values. Inheritance allows classes to inherit and extend the functionality of other classes. The document provides examples of how to define classes, objects, methods, and illustrates object-oriented concepts.

Uploaded by

Karan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views89 pages

EE3206 Java Programming and Applications: Lecture 4. Object-Oriented Programming (Classes, Objects, Inheritance)

This document discusses object-oriented programming concepts including classes, objects, methods, and inheritance. It begins by explaining that classes are templates used to create objects which have both state (data fields) and behavior (methods). Methods are functions that can be called on objects and can accept parameters and return values. Inheritance allows classes to inherit and extend the functionality of other classes. The document provides examples of how to define classes, objects, methods, and illustrates object-oriented concepts.

Uploaded by

Karan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

EE3206

Java Programming and Applications

Lecture 4. Object-oriented programming


(classes, objects, inheritance)
OOP (Object-oriented programming)
• This will be a two-part section on object-oriented programming (OOP).

• In Part one, we will learn fundamental structures of OOP;

• Classes, Objects, and Constructor

• In Part two, we will learn four pillars of OOP;

• Inheritance, Encapsulation, Polymorphism, and Abstraction.


Four Pillars of the OOP
OOP and Object
• Object means a real-world entity such as a pen, chair, table, computer, watch, etc.

• Object-Oriented Programming is a methodology or paradigm to design a program using


classes and objects. It simplifies software development and maintenance.

• 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();

• The state of an object consists of a set of data fields


(also known as properties) with their current values.
• peter.age // data field
• peter.sid
• peter.gpa

• The behavior of an object is defined by a set of


methods.
• peter.graduate() // methods
• peter.promoteToNextYear()
Class
• A class is a group of objects which have common properties.

• It is a logical entity. It can’t be physical.

• A class is a template or blueprint from which objects are created.


→ An object is the instance(result) of a class.

• Class doesn't consume any space.

• A class can contain:


• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Method
• A method declares executable code that can be invoked, passing a fixed number of
values as arguments.

• Advantage of Method

• Code Reusability

• Code Optimization

• Reduce code duplication


Method Syntax – 1 (No input, No return)
• This method has a name, but takes no data in, and returns no data from the method
(which is what void means in this declaration).
Calling the method
• Executing a method = calling, or invoking, the method

• 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).

Input parameters (arguments)

• 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)

Data type of the returned value

• 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.

• It should start with lowercase letter.


• It should be a verb such as main(), print(), println().
• If the name contains multiple words, start it with a lowercase letter followed by an
uppercase letter such as actionPerformed().

• Input Parameters Declaration: Parameters are declared as a list of comma-separated


specifiers, each of which has a parameter type and a parameter name (or identifier).
Return Statement for methods with a return type

• 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[]) {

System.out.println("Welcome to the Calculator");


Scanner scan=new Scanner(System.in); //creating Scanner class object
int a = 5; System.out.print("Enter the number: "); //reading value from user
int b = 10; int num=scan.nextInt();
System.out.println(a*b);

multiply(5, 10); findEvenOdd(num); //method calling


multiply(3, 2); }

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 { }

static void myMethod(String fname, int age) { }


System.out.println(fname + " is " + age);
public static void main(String[] args) {
} checkAge(20); // Call the checkAge method and pass along an age of 20
}
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Class Syntax
• Syntax to declare a class:

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

//Printing values of the object


System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}

• 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{

public static void main(String args[]){


Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

• 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

• Also, the memory size of the stack is fixed and limited.

• Every method has their own Stack.


Stack and Heap Memory in Java
• Heap
• heap is a section of memory that allows dynamic allocation of memory, so it does not
follow any order (such as LIFO).

• 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 is slower than Stack.

• Objects are created dynamically on the heap memory.


• Reference variables hold the memory address of these objects.

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();

s1.id=101; s1.name="Sonoo"; //Initializing objects


s2.id=102; s2.name="Amit";

//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;

void insertRecord(int r, String n){ rollno=r; name=n; }


void displayInformation(){System.out.println(rollno+" "+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;

void insert(int l, int w){


length=l; width=w;
}
void calculateArea(){System.out.println(“The area of the Rectangle is ” + length*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.

• Initialization primitive variables

Ex) int a=10, b=20;

• Initialization of reference variables

Ex) Rectangle r1=new Rectangle(), r2=new Rectangle();

• We can create multiple objects in a single statement.


Method Types
• Predefined Method
• method that is already defined in the Java class
libraries

• known as the standard library method or built-in


method

• User-defined Method
• method written by the user or programmer

• User-defined methods are modified according to


the requirement
Method Types
• Static Method (-> Class)
• A method that has static keyword is known as static method. We can create a static
method by using the keyword static before the method name.

• A method that belongs to a class rather than an instance of a class is a static method.

• We can call a static method without creating an object.

• Instance Method (-> Object)


• It is a non-static method defined in the class.

• Before calling or invoking the instance method, it is necessary to create an object of


its class.
Example on Static Method
• As ‘show()’ is a static method, we can call it without creating an object.

public class Display


{
public static void main(String[] args)
{
show();
}

static void show() {


System.out.println("It is an example of static method.");
}
}
Example on Instance Method

public class InstanceMethodExample


{
public static void main(String [] args)
{
InstanceMethodExample obj = new InstanceMethodExample(); //Creating an object
System.out.println("The sum is: "+obj.add(12, 13));
}

int s;

public int add(int a, int b) //Instance method as there is no static keyword


{
s = a+b;
return s;
}
}
Static Keyword v.s. Instance Keyword
• The static keyword belongs to the class, whereas instance keyword belongs to the
instance of the class (a.k.a. Object).

• 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

public class Example1 {

int a = 0; // Change to static int a = 0;

public static void main(String[] args) {


int b = 1;
// System.out.println(a);
//this statement works without creating an object

Example1 s = new Example1();


System.out.println(s.a);
}
}
Example of Static Method
class Calculate{
static int cube(int x){ //Once you remove ‘static’, the code will not work
return x*x*x;
}

public static void main(String args[]){

int result=Calculate.cube(5);
System.out.println(result);
}
}
Example of Static Variable
class Example {
static int count = 0;

public Example() { //We put a counter inside the constructor


count++;
}

public static void main(String[] args) {


Example obj1 = new Example();
Example obj2 = new Example();
Example obj3 = new Example();
System.out.println("Number of objects created: " + Example.count);
}
}

• 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;

public Circle(double r) { //Constructor


radius = r;
}

public double area() { //Method


return pi * radius * radius;
}

public static void main(String[] args) {


Circle c1 = new Circle(5);
Circle c2 = new Circle(7);
System.out.println("Area of circle 1: " + c1.area());
System.out.println("Area of circle 2: " + c2.area());
}
}
Example of Non-Static Variable
class BankAccount {
private int accountNumber; private String accountHolderName; private double balance;

public BankAccount(int accountNumber, String accountHolderName, double balance) {


this.accountNumber = accountNumber; this.accountHolderName = accountHolderName;
this.balance = balance;
}

public int getAccountNumber() { return accountNumber; }


public String getAccountHolderName() { return accountHolderName; }
public double getBalance() { return balance; }

public void displayAccountInfo() {


System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder Name: " + accountHolderName);
System.out.println("Balance: $" + balance }
}
class Example1{
public static void main(String args[]){
BankAccount account1 = new BankAccount(12345, "John Doe", 5000.0); account1.displayAccountInfo();

BankAccount account2 = new BankAccount(67890, "Jane Doe", 6000.0); account2.displayAccountInfo();


}
}
Method Overloading
• Method overloading allows a class to have more than one method with the same name,
but with different parameters.

• Java supports method overloading through two mechanisms:


• By changing the number of parameters

• By changing the data type of parameters


Example on Method Overloading
class Adder{
static int add(int a, int b){return a+b;}
//Changing the Data type (int -> double)
static double add(double a, double b){return a+b;}
//Changing the number of parameter
static int add(int a,int b,int c){return a+b+c;}
}

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.

• It is a special type of method which is used to initialize the object.

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.

• Syntax of default constructor: <class_name>(){}

• If there is no constructor in a class, compiler automatically creates a default


constructor.
Example of Default Constructor
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){ //constructor without any parameter is a default constructor
System.out.println("Bike is created");
}

//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.

• The parameterized constructor is used to provide different values to distinct objects.

• If there is no constructor in a class, compiler automatically creates a default


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;

Student4(int i, String n){ //creating a parameterized constructor


id = i; name = n; }

void display(){ //method to display the values


System.out.println(id+" "+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);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display(); s2.display();
}
}
Constructor
• Constructors must have the same name as the class itself.
• Constructors do not have a return type — not even void.

• 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).

• Two common usages:


• To explicitly refer to an instance’s data field.

• To invoke an overloaded constructor of the same class.

• 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

• A class is said to be a top-level class, if it is defined in the


source code file, and not enclosed in the code block of another
class, type, or method.

• A top-level class has only two valid access modifier options:


public, or none.
Access modifiers for class members
• Access modifier for class members specifies the accessibility of a field, method, and
constructor.
• Private: access level is only within the class. It cannot be accessed from outside the
class.
• Default: access level is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
• Protected: access level is within the package and outside the package through child
class. If you do not make the child class, it cannot be accessed from outside the package.
• Public: access level is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
Example
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}

• 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
}

//save in B.java file within package2

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;

public void setVariable(int x){ //Setter


this.variable=x;
}

public int getVariable{ //Getter Method


return variable; }
}
Example on Getter and Setter
class Vehicle {
private String color;
// Getter
public String getColor() {
return color; }
// Setter
public void setColor(String color) {
this.color = color; }
}

public class Example2 {


public static void main(String[] args) {
Vehicle v1 = new Vehicle();
v1.setColor("Red");
System.out.println(v1.getColor());
}
}
Exercise Problem
• Write a Java method to find the smallest number among three numbers.

• public class Exercise1 {


public static void main(String[] args)
{
double x = 100, y = 150, z = 300;
System.out.println("The smallest value is " + smallest(x, y, z));
}

public static double smallest(double x, double y, double z)


{
return Math.min(Math.min(x, y), z);
}
}
Exercise Problem
• Write a Java method to display an n-by-n matrix with only 0 and 1 elements

public class Exercise2 {

public static void main(String[] args)


{
int n = 10;
printMatrix(n);
}

public static void printMatrix(int n) {

for(int i = 0; i < n; i++) {


for(int j = 0; j < n; j++) {
System.out.print((int)(Math.random() * 2) + " ");
}
System.out.println();
}
}
}
Review & Overview

• Static / Instance Method review


• Access Modifiers
• Getter / Setter

• 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)

• Relationship between A and B is described as


• Child (A) and Parent (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.

• You may further:


• Add new fields and methods
• Some properties the parent do not have
• Some behaviors the parent do not have
• Override the methods inherited from the superclass
• i.e. rewrite the method defined in the parent
• Usually happen when the inherited method is not appropriate if it applies to the subclass
[1] OOP - Inheritance
• Inheritance Syntax
class child_class extends parent_class
{
//methods
//fields
}

• General format for Inheritance


class​ superclass
{
// superclass data variables
// superclass member functions
}
class​ subclass ​extends​ superclass
{
// subclass data variables
// subclass member functions
}
Examples of Inheritance
• Mouse1.java file • Mouse2.java file • Mouse3.java file
public class Mouse1 extends Mouse { public class Mouse2 extends Mouse{ public class Mouse3 extends Mouse {

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

public class Mouse { public class Main {


public static void main(String[] args) {
public static void leftClick() {
System.out.println("left clicked!");
} Mouse1 m1 = new Mouse1();
System.out.println(m1.Texture);
public static void rightClick() { m1.leftClick(); m1.rightClick();
System.out.println("right clicked!"); m1.upWheel(); m1.downWheel();
}
Mouse2 m2 = new Mouse2();
public static void upWheel() { m2.connect();
System.out.println("scroll Up!");
} m2.leftClick(); m2.rightClick();
m2.upWheel(); m2.downWheel();
public static void downWheel() {
System.out.println("scroll Down!"); Mouse3 m3 = new Mouse3();
} m3.highResolutionSensing();
}
}
}
Ref: Alex Lee’s Youtube Video on Inheritance
Examples of Inheritance
class Employee{
int 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);
}
}
[1] OOP - Inheritance
• Types of Inheritance
• There are be three types of inheritance in java: single, multilevel and hierarchical.

• Multiple and hybrid inheritance is supported through interface only.


Examples of Single Inheritance
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();
}}
Example of Multilevel Inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep(); d.bark(); d.eat();
}}
Example of Hierarchical Inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow(); c.eat(); //c.bark() will cause an error
}}
Super Keyword
• The keyword this is a reference to the current object context (i.e. the executing object).

• 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.

• NOTE: We can not use This or Super keywork in static elements.


Example of This Keyword
In this example, we're using this keyword in the constructor and setter
Example of Super Keyword
The keyword super, is commonly used with method overriding, when we call a method with
the same name, from the parent class.
This() vs. Super() call
• This () and Super() call are used in a constructor.

• This() is used to call a constructor, from another overloaded constructor in the same
class.

• super() is used to call the parent constructor.

• this() and Super() call must be the first statement in a constructor. Otherwise, it causes
compile error.
Constructors Bad Example

Here, we have three constructors.

All three constructors initialize variables.

There's repeated code in each constructor.

We're initializing variables in each constructor,


with some default values.

You should never write constructors like this.

Let's look at the right way to do this, by using a


this() call.
Constructors Good Example

In this example, we still have three


constructors.
The 1st constructor calls the 2nd constructor,
the 2nd constructor calls the 3rd constructor,
and the 3rd constructor initializes the instance
variables.
The 3rd constructor does all the work.
No matter what constructor we call, the
variables will always be initialized in the 3rd
constructor.
This is known as constructor chaining, the last
constructor has the responsibility to initialize
the variables.
super() call example

In this example, we have a class Shape, with x


and y variables, and a class Rectangle that
extends Shape, with variables width and
height.
In the Rectangle class, the 1st constructor is
calling the 2nd constructor.
The 2nd constructor calls the parent
constructor, with parameters x and y.
The parent constructor will initialize the x and y
variables, while the 2nd Rectangle constructor
will initialize the width and height variables.
Here, we have both the super() and this()
calls.
java.lang.Object class
• Every class in Java is descended from the java.lang.Object class. If no inheritance is
specified when a class is defined, the superclass of the class is Object.

• 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.

• We can perform Polymorphism in Java via two different methods


• Method Overloading: process that can create multiple methods of the same name
within the same class, and all the methods work in different ways.

• 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.

• animalSound method is overrided at the


child-class Pig and Dog (method overriding)
Example of Polymorphism
• Method Overloading (within the same class)

• Method name is the same, but

• Method signature is different


Example of Polymorphism
• Method Overriding (across IS-A classes)
• Name and parameter of the method are
the same (Same method signature), but

• There is a parent-child relationship


between the classes

❖IS-A is a way of saying that two class has a


parent-child relationship.
Useful API
• Scanner Class

• You can get input from console using Scanner object:


1. Create a Scanner object (the counterpart of scanf() in C language)

• Scanner scanner = new Scanner(System.in);

2. Use these methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(),


nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double,
or boolean value. For example,
• System.out.print("Enter a double value: ");
• Scanner scanner = new Scanner(System.in);
• double d = scanner.nextDouble();

You might also like