INFO410-1
INFO410-1
1
class Laptop {
Laptop() {
void laptop_method() {
} }
Computer() {
void computer_method() {
my.computer_method();
your.laptop_method();
2
public class RunEncap{
encap.setName(“John");
encap.setAge(31);
encap.setIdNum(“582144");
} 3
Encapsulation
• Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation the variables of a
class will be hidden from other classes, and can be accessed only through the methods
of their current class, therefore it is also known as data hiding.
• The principle of encapsulation dictates that an object should have total control of its
data. That is, another object should not change the data without the owner knowing.
• This is achieved in java by declaring instance variables as private.
• It is the bringing together of data and operations - Encapsulation.
• To achieve encapsulation in Java
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and view the variables values.
• A method that changes the value of some instance variable is called a mutator
method.
4
Encapsulation
5
Accessor and mutator methods
• Accessor methods are public methods that allow the programmer to obtain the
value of an object's instance variables
• The data can be accessed but not changed
• The name of an accessor method typically starts with the word get
• The name of a mutator method typically starts with the word set
• Sometimes an object cannot help but provide methods that changes the
values of its variables. Such methods are called Mutator methods
6
Example Code
public class Student{
private String name;
}
7
public class EncapTest{ }
age = newAge;
private String idNum;
}
private int age;
public void setName(String
public int getAge(){
newName){
return age; } name = newName; }
public String getName(){
public void setIdNum( String
return name; } newId){
public String getIdNum(){ idNum = newId;
return idNum; }
8
public class RunEncap{
encap.setName(“Simba");
encap.setAge(31);
encap.setIdNum(“582144");
9
Example 2
class Student{
String id;
id = _id;
totalScore = 0; }
return totalScore;
totalScore += score;
numOfQuizes++;
}
10
}
public class Teste {
t.addQuiz(85);
//t.getTotalScore();
System.out.println(t.toString());
}
11
Inheritance
• Inheritance can be defined as the process where one class acquires
the properties (methods and fields) of another. With the use of
inheritance the information is made manageable in a hierarchical
order.
• The class which inherits the properties of another class is known as
subclass (derived class, child class) and the class whose properties
are inherited is known as superclass (base class, parent class).
• Inheritance represents the IS-A relationship, also known as parent-
child relationship.
13
Inheritance Syntax
class Super{
.....
.....
The extends keyword indicates that you are making a new class
that derives from an existing class.
•In the terminology of Java, a class that is inherited is called a super
class. The new class is called a subclass.
14
Syntax with code snippets
15
Rules for Inheritance
16
Example
class Super_class{
int num=20;
int num=10;
//Instantiating subclass
17
Example 2
public class A {
int x,y,z;
System.out.print("Java");
int d;
int f;
A a= new A();
B b= new B();
C c= new C();
b.x= 0;
c.f();
18
}}
Question 1
1. Create a class, Person, with an instance variable, name. Write appropriate
accessor and mutator methods for the class. Also write a toString method for the
class.
2. Employee, that extends Person, and has: two additional instance variables, ID and
payRate; and an additional method, pay, that returns the payRate. Override the
toString method accordingly.
3. Faculty, that extends Employee, and has two additional variables; officeHours of
type String and teachingCourses, which is an array of Courses. Each course has
course code and course title. Write appropriate accessor, mutator and toString
methods for the class.
4. TestPersons, that has two methods: void printPerson(Person p) that prints its
argument. And a main method that creates an instance of each of the above
classes and prints it using printPerson method.
19
Inheritance and Constructors
• Since constructors cannot be inherited within the subclass there is need to have reference
super class members within the sub class
• We use the super() keyword to access such members
• If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the super class. But if you want to call a parameterised constructor of the
super class, you need to use the super keyword as shown below.
• super(values);
20
Inheritance and Constructors cont’d
class Superclass{
int age;
Superclass(int age){
this.age=age;
System.out.println("The value of the variable named age in super class is: " +age);
Subclass(int age){
super(age);
s.getAge();
} 21
Inheritance and Constructors Example 2
class Student {
private long id;
private String name;
private double gpa;
public Student(long id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}
public Student() {
this(999999, "No name", 0.0);
}
public void changeGPA(double newGPA) {
gpa = newGPA;
}
public double getGPA() {
return gpa;
}
public void print() {
System.out.print(id+" "+name+ " "+gpa);
}
}
22
Inheritance and Constructors Example 2
class ResearchAssistant extends Student {
private int workLoad; // in hours
ResearchAssistant(long id, String name, double gpa,int workLoad){
super(id, name, gpa);
this.workLoad = workLoad;
}
ResearchAssistant() {
super();
workLoad = 0;
}
public void print() {
super.print();
System.out.print(" " + workLoad);
}
}
class TestReserchAssistant {
public static void main (String[] args) {
ResearchAssistant s1 = new
ResearchAssistant();
s1.print();
ResearchAssistant s2 = new ResearchAssistant(991234, "Al-Ghamdi Ahmed",3.45,15);
s2.changeGPA(3.75);
s2.print();
}
}
23
Practice Question 1
a) Create a class called Customer which contains personal details of such as AccNo,
Name, Address. Include a constructor which is parameterised and get methods for
each variable. Given that Bill is derived from Customer. Bill class also contains
variables fixed_charge which is static being equal to 13.00, units and rate.
b) Demonstrate how we can access the constructor you created in a within Bill
constructor
c) Bill also contains a method which calculates the bill using the formula: bill=
fixed_charge+ units*rate
d) Create your instance within the main to display the customer details and the bill due.
The program should accept user input.
24
Practice Question 2
25
Multilevel Inheritace
class A{
int x;
class B extends A{
int y;
class C extends B{
int p;
public C() {
x=15;
y=340;
p= x+y;
void display(){
System.out.println();
} 26
Multilevel Inheritace
C X= new C();
X.display();
27
Example
class Person
String FirstName;
String LastName;
{ FirstName = fName;
LastName = lName;
void Display()
28
Example
class Student extends Person
int id;
String standard;
String instructor;
Student(String fName, String lName, int nId, String stnd, String instr)
super(fName,lName);
id = nId;
standard = stnd;
instructor = instr;
void Display()
{ super.Display();
}}
29
Example
class Teacher extends Person
String mainSubject;
int salary;
Teacher(String fName, String lName, String sub, int slry, String sType)
super(fName,lName);
mainSubject = sub;
salary = slry;
type = sType;
void Display()
super.Display();
}}
class InheritanceDemo
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
30
Example
class Teacher extends Person
{String mainSubject;
int salary;
Teacher(String fName, String lName, String sub, int slry, String sType)
{ super(fName,lName);
mainSubject = sub;
salary = slry;
type = sType;
void Display()
super.Display();
}}
31
Example
class InheritanceDemo
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
System.out.println("Teacher :");
tObj.Display();
32
Polymorphisn
• Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
• There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method overriding.
• If you overload static method in java, it is the example of compile time polymorphism. Here, we will
focus on runtime polymorphism in java.
• In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
33
RunTime Polymorphism
• The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a
subclass can implement a parent class method based on its requirement. In object oriented terms, overriding
means to override the functionality of any existing method.
Rules for method overriding:
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original overridden method in
the super class.
• The access level cannot be more restrictive than the overridden method's access level. For example: if the super
class method is declared public then the overridding method in the sub class cannot be either private or
protected. However the access level can be less restrictive than the overridden method's access level.
• A method declared final cannot be overridden.
• A subclass within the same package as the instance's superclass can override any superclass method that is
not declared private or final.
• A subclass in a different package can only override the non-final methods declared public or protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws
exceptions or not. However the overridden method should not throw checked exceptions that are new or broader
than the ones declared by the overridden method. The overriding method can throw narrower or fewer
exceptions than the overridden method.
• Constructors cannot be overridden.
34
RunTime Polymorphism
Upcasting
•When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
class A{ }
class B extends A{}
A a=new B();//upcasting
35
RunTime Polymorphism
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
36
RunTime Polymorphism
class Animal{
37
class Animal{
public void move(){ RunTime Polymorphism
System.out.println("Animals can move");
}}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}}
This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of
bark.
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
38
Polymorphic Arrays, inheritance and Overrding
• It is possible for a parent class to reference subclass members using a Polymorphic Array.
class Shape{
protected double dim1, dim2;
public Shape(double dim1, int dim2) {
this.dim1 = dim1;
this.dim2 = dim2;
}
public double calcArea(){
return 1;
}
}
class Rectabgle extends Shape{
public Circle(double dim1, int dim2) {
super(dim1, dim2);
}
public double calcArea(){
double area;
area= 2*(dim1+ dim2);
String s= getClass().getSimpleName();
System.out.println("Areas for : " + s + "==" + area );
return area; }
39
Polymorphic Arrays, inheritance and Overrding
}
public class Sim23{
public static void main(String [] args){
Shape a[]= new Shape[2];
Triangle t= new Triangle(12,15);
super();
super.variable;
super.method(…);
41
Super in variables
class A {
int i = 1;
class B extends A {
int i;
B(int a, int b) {
super.i = a; i = b;
void show() {
class UseSuper {
subOb.show();
42
Super in Methods
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
}
public class TestDog{
}
}
This would produce following result:
Animals can move
Dogs can walk and run
43
Super in Methods 2
class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A {
int j;
B(int a, int b, int c) {
super(a, b);
j = a+b+c;
}
void add() {
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding {
public static void main(String args[]) {
45
Method Overloading
Method 1
class Calculation{
obj.sum(10,10,10);
obj.sum(20,20);
Method 2
class Calculation2{
obj.sum(10.5,10.5);
obj.sum(20,20);
}
46
}
Method Overloading
In java, method overloading is not possible by changing the return type of the method because there may occur
ambiguity. Let's see how ambiguity may occur:
class Calculation3{
47
Method Overloading vs Overriding
48
Abstraction
-A Class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-
abstract methods (method with body).
Abstraction in Java
-Abstraction is a process of hiding the implementation details and showing only functionality to the user.
-Another way, it shows only important things to the user and hides the internal details for example sending sms, you
just type the text and send the message. You don't know the internal processing about the message delivery.
-Abstraction lets you focus on what the object does instead of how it does it.
2. Interface (100%)
49
Abstract Classes
• A class must be declared abstract when it has one or more abstract methods. A method is declared abstract
when it has a method heading, but no body – which means that an abstract method has no implementation code
inside curly braces like normal methods do.
• -Abstract classes in Java are classes which cannot be instantiated, meaning you cannot create new instances of
an abstract class. The purpose of an abstract class is to function as a base for subclasses.
• -When we define a class to be “final”, it cannot be extended. In certain situation, we want to properties of classes
to be always extended and used. Such classes are called Abstract Classes.
• An Abstract class is a conceptual class.
• -An Abstract class cannot be instantiated – objects cannot be created.
• -Abstract classes provides a common root for a group of classes, nicely tied together in a –package
50
Abstract Classes
abstract class ClassName
...
Type Method2()
// method body
} }
51
Example
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
52
Example
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
53
Example 2
abstract class Bank{
class TestBank{
int interest=b.getRateOfInterest();
Implement the concept of abstraction for classes Mercedes Benz, Mazda and Nissan classes.
55
Java Interfaces
• Using interface, we specify what a class must do, but not how it does this.
• Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the
interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly
public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated
but upcasting is allowed
• Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces.
3. Methods are declared without a body (abstract methods) and can either be declared with or without the abstract keyword
56
Java Interfaces
• Using interface, we specify what a class must do, but not how it does this.
• The objective is to attempt to achieve multiple inheritance
• Interface can be used to define a generic template and then one or more abstract classes to define partial
implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can
only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface
like that of an abstract class cannot be instantiated but upcasting is allowed
• Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces.
• Interfaces have the following properties
• Can contain final variables, which must be initialized with values.
2. Methods are declared without a body (abstract methods) and can either be declared with or without the abstract keyword
57
Java Interfaces
Interface Format
Syntax :
• When no access specifier is used, it results into default access specifier and if interface has default access specifier then it is only
available to other members of the same package.
• When it is declared as public, the interface can be used by any other code of other package
58
Java Interfaces Examples
interface Item
void display ( );
interface Area
void show ( );
59
Java Interfaces Examples
interface religion
void greet();
void pray();
} }
60
Java Interfaces Examples
class iface1
sikh.greet();
sikh.pray();
61
Java Interface and Multiple Inheritance
interface Printable{
void print();
interface Showable{
void show();
obj.print();
obj.show();
62
Java Interface Inheritance
nterface Printable{
void print();
void show();
obj.print();
obj.show();
63
Java Interface extending another interface
interface Area{
double calcArea();
area= calcArea();
return area*70;
obj.calcArea();
System.out.println(obj.paint(obj.calcArea()));
} 64
Difference between abstract class and interface
65
Aggregation
• If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
• Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one
more object named address, which contains its own informations such as city, state, country, zipcode etc. as
given below.
• Aggregation is meant to promote Code Reusability.
Example of Aggregation
66
Aggregation Example 1
class Operation{
return n*n;
class Circle{
Operation op;//aggregation
double pi=3.14;
op=new Operation();
return pi*rsquare;
double result=c.area(5);
System.out.println(result);
}
67
Aggregation Example 2
In this example, Employee has an object of Address, address object contains its own informations such as city, state,
country etc. In such case relationship is Employee HAS-A address.
String city,state,country;
this.city = city;
this.state = state;
this.country = country;
int id;
String name;
this.id = id;
this.name = name;
this.address=address;
68
Aggregation Example 2
void display(){
System.out.println(id+" "+name);
e.display();
69
Arraylist
-An arraylist is a special type of array which stores elements of different
data types.
-The data types are of wrapper class types
-A ArrayList is like an array of Objects, but...
-Arrays use [ ] syntax; ArrayLists use object syntax
-An ArrayList expands as you add things to it
-Arrays can hold primitives or objects, but ArrayLists can only hold
objects
70
Arraylist
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
71
Arraylist
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
72
Generic Programming
• Generics can be applied to the follwing
Wrapper Classes
• Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.
• Autoboxing and unboxing feature converts primitive into object and object into primitive automatically.
The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
• One of the eight classes of java.lang package are known as wrapper class in java. The list of eight wrapper
classes are given below.
• Java won’t let you use a primitive value where an object is required--you need a “wrapper”
– ArrayList<Integer> myList = new ArrayList<Integer>();
– myList.add(new Integer(5));
• Similarly, you can’t use an object where a primitive is required--you need to “unwrap” it
– int n = ((Integer)myArrayList.get(2)).intValue();
73
Generic Programming
Wrapper class Example: Primitive to Wrapper
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
Wrapper class Example: Wrapper to Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Product{
int id;
String name;
float price;
super();
this.id = id;
this.name = name;
this.price = price;
}
75
Java Lambda Expression Example: Collections Framework
public class LambdaExpressionExample10{
//Adding Products
list.add(new Product(3,"Keyboard",300f));
Int n = list.size();
System.out.println(liist.get(i). toString());
76