SlideShare a Scribd company logo
1 of 43
Download to read offline
www.webstackacademy.com
Java Programming Language SE – 6
Module 6 : Class Design
www.webstackacademy.com
Objectives
● Define inheritance, polymorphism, overloading, overriding, and virtual
method invocation
● Use the access modifiers protected and the default
(package-friendly)
● Describe the concepts of constructor and method overloading
● Describe the complete object construction and initialization operation
www.webstackacademy.com
Relevance
● How does the Java programming language support object
inheritance?
www.webstackacademy.com
Subclassing
The Employee class is shown here.
www.webstackacademy.com
Subclassing
The Manager class is shown here.
www.webstackacademy.com
Employee and Manager
Using Inheritance
www.webstackacademy.com
Single Inheritance
● When a class inherits from only one class, it is called
single inheritance.
● Interfaces provide the benefits of multiple inheritance
without drawbacks.
● Syntax of a Java class is as follows:
<modifier> class <name> [extends <superclass>] {
<declaration>*
}
www.webstackacademy.com
Single Inheritance
www.webstackacademy.com
Access Control
● Access modifiers on class member declarations are listed here.
www.webstackacademy.com
Overriding Methods
● A subclass can modify behavior inherited from a parent class.
● A subclass can create a method with different functionality than the
parent’s method but with the same:
– Name
– Return type
– Argument list
www.webstackacademy.com
Overriding Methods
public class Employee {
protected String name;
protected double salary;
protected Date birthDate;
Public String getDetails(){
Return “Name:”+name+”n”+”Salary:”+salary;
}
}
www.webstackacademy.com
Overriding Methods
public class Manager extends Employee {
protected String department;
public String getDetails() {
return “Name: “ + name + “n” +
“Salary: “ + salary +”n” +”Manager of:”+ department;
}
}
www.webstackacademy.com
Rules of Method Overriding
Overridden methods can't be less accessible.
public class Parent {
public void doSomething() {}
}
public class Child extends Parent {
private void doSomething() {} // illegal
}
www.webstackacademy.com
Invoking Overridden
Methods
A subclass method may invoke a superclass method using the super
keyword:
● The keyword super is used in a class to refer to its superclass.
● The keyword super is used to refer to the members of superclass,
both data attributes and methods.
● Behavior invoked does not have to be in the superclass; it can be
further up in the hierarchy.
www.webstackacademy.com
Invoking Overridden
Methods
public class Employee {
protected String name;
protected double salary;
protected Date birthDate;
public String getDetails(){
return “Name:”+name+”n”+”Salary:”+salary;
}
}
www.webstackacademy.com
Invoking Overridden
Methods
public class Manager extends Employee {
protected String department;
public String getDetails() {
//call parent method
return super.getDetails()+”nDepartment:”+ department;
}
}
www.webstackacademy.com
Polymorphism
● Polymorphism is the ability to have many different forms; for example,
the Manager class has access to methods from Employee class.
● An object has only one form.
● A reference variable can refer to objects of different forms.
www.webstackacademy.com
Polymorphism
www.webstackacademy.com
Polymorphism
Employee e = new Manager(); // legal
// illegal attempt to assign Manager attribute
e.department = "Sales";
// the variable is declared as an Employee type,
// even though the Manager object has that attribute
www.webstackacademy.com
Virtual Method Invocation
● Virtual method invocation is performed as follows:
Employee e = new Manager();
e.getDetails();
● Compile-time type and runtime type invocations have the
following characteristics:
● The method name must be a member of the declared variable
type; in this case Employee has a method called getDetails.
● The method implementation used is based on the runtime
object’s type; in this case the Manager class has an
implementation of the getDetails method.
www.webstackacademy.com
Homogeneous Collections
● Collections of objects with the same class type are called
homogeneous collections. For example:
MyDate[] dates = new MyDate[2];
dates[0] = new MyDate(22, 12, 1964);
dates[1] = new MyDate(22, 7, 1964);
www.webstackacademy.com
Heterogeneous Collections
● Collections of objects with different class types are called
heterogeneous collections. For example:
Employee [] staff = new Employee[1024];
staff[0]= new Manager();
staff[1]= new Employee();
staff[2]= new Engineer();
www.webstackacademy.com
Polymorphic Arguments
Because a Manager is an Employee, the following is valid:
public class TaxService {
public TaxRate findTaxRate(Employee e) {
// calculate the employee’s tax rate
}}
// Meanwhile, elsewhere in the application class
TaxService taxSvc = new TaxService();
Manager m = new Manager();
TaxRate t = taxSvc.findTaxRate(m);
www.webstackacademy.com
The instanceof Operator
public class Employee extends Object
public class Manager extends Employee
public class Engineer extends Employee
----------------------------------------
public void doSomething(Employee e) {
if ( e instanceof Manager ) {
// Process a Manager
} else if ( e instanceof Engineer ) {
// Process an Engineer
} else {
// Process any other type of Employee
}}
www.webstackacademy.com
Casting Objects
public void doSomething(Employee e) {
if ( e instanceof Manager ) {
Manager m = (Manager) e;
System.out.println(“This is the manager of ”
+ m.getDepartment());
}
// rest of operation
}
www.webstackacademy.com
Casting Objects
● Use instanceof to test the type of an object.
● Restore full functionality of an object by casting.
● Check for proper casting using the following guidelines:
● Casts upward in the hierarchy are done implicitly.
● Downward casts must be to a subclass and checked by the compiler.
● The object type is checked at runtime when runtime errors can occur.
www.webstackacademy.com
Overloading Methods
● Use overloading as follows:
– public void println(int i)
– public void println(float f)
– public void println(String s)
● Argument lists must differ.
● Return types can be different.
www.webstackacademy.com
Methods Using Variable
Arguments
public float average(int... nums) {
int sum = 0;
for ( int x : nums ) {
sum += x;
}
return ((float) sum) / nums.length;
}
● The vararg parameter is treated as an array. For
● Example: float gradePointAverage = stats.average(4, 3, 4);
www.webstackacademy.com
Overloading Constructors
● As with methods, constructors can be overloaded.
An example is:
public Employee(String name, double salary, Date DoB)
public Employee(String name, double salary)
public Employee(String name, Date DoB)
● Argument lists must differ.
● You can use the this reference at the first line of a constructor to call
another constructor.
www.webstackacademy.com
Constructors Are Not
Inherited
● A subclass inherits all methods and variables from the superclass
(parent class).
● A subclass does not inherit the constructor from the superclass.
• Two ways to include a constructor are:
• Use the default constructor.
• Write one or more explicit constructors.
www.webstackacademy.com
Invoking Parent Class
Constructors
● To invoke a parent constructor, you must place a call to super in the
first line of the constructor.
● You can call a specific parent constructor by the arguments that you
use in the call to super.
● If no this or super call is used in a constructor, then the compiler adds
an implicit call to super() that calls the parent no argument
constructor (which could be the default constructor).
If the parent class defines constructors, but does not provide a no-
argument constructor, then a compiler error message is issued.
www.webstackacademy.com
The Object Class
● The Object class is the root of all classes in Java.
● A class declaration with no extends clause implies
extends Object. For example:
public class Employee {
...
}
is equivalent to:
public class Employee extends Object {
...
}
www.webstackacademy.com
The Object Class
● Two important methods are:
– equals
– toString
www.webstackacademy.com
The equals Method
● The == operator determines if two references are identical to each
other (that is, refer to the same object).
● The equals method determines if objects are equal but not
necessarily identical.
● The Object implementation of the equals method uses the ==
operator.
● User classes can override the equals method to implement a domain-
specific test for equality.
● Note: You should override the hashCode method if you override the
equals method.
www.webstackacademy.com
An equals Example-1
public class MyDate {
private int day;
private int month;
private int year;
public MyDate(int day, int month, int year) {
this.day= day;
this.month = month;
this.year = year;
}
www.webstackacademy.com
An equals Example-1
public boolean equals(Object o) {
boolean result = false;
if ( (o != null) && (o instanceof MyDate) ) {
MyDate d = (MyDate) o;
if ( (day == d.day) && (month == d.month)
&& (year == d.year) ) {
result = true;
}}
return result;
}
public int hashCode() {
return (day ^ month ^ year);
}}
www.webstackacademy.com
An equals Example-2
class TestEquals {
public static void main(String[] args) {
MyDate date1 = new MyDate(14, 3, 1976);
MyDate date2 = new MyDate(14, 3, 1976);
if ( date1 == date2 ) {
System.out.println("date1 is identical to date2");
} else {
System.out.println("date1 is not identical to date2");
}
if ( date1.equals(date2) ) {
System.out.println("date1 is equal to date2");
} else {
System.out.println("date1 is not equal to date2");
}
www.webstackacademy.com
An equals Example-2
System.out.println("set date2 = date1;");
date2 = date1;
if ( date1 == date2 ) {
System.out.println("date1 is identical to date2");
} else {
System.out.println("date1 is not identical to date2");
}}}
www.webstackacademy.com
The toString Method
The toString method has the following characteristics:
● This method converts an object to a String.
● Use this method during string concatenation.
● Override this method to provide information about a user-defined
object in readable format.
● Use the wrapper class’s toString static method to convert primitive
types to a String.
www.webstackacademy.com
Wrapper Classes
Look at primitive data elements as objects.
www.webstackacademy.com
Wrapper Classes
● An example of a wrapper class is:
int pInt = 420;
Integer wInt = new Integer(pInt); // this is called boxing
int p2 = wInt.intValue(); // this is called unboxing
● Other methods are:
int x = Integer.valueOf(str).intValue();
int x = Integer.parseInt(str);
www.webstackacademy.com
Autoboxing of Primitive
Types
Autoboxing has the following description:
• Conversion of primitive types to the object equivalent
• Wrapper classes not always needed
• Example:
int pInt = 420;
Integer wInt = pInt; // this is called autoboxing
int p2 = wInt; // this is called autounboxing
• Language feature used most often when dealing with collections
• Wrapped primitives also usable in arithmetic expressions
• Performance loss when using autoboxing
www.webstackacademy.com
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com

More Related Content

What's hot

4.trasformers filters-adapters
4.trasformers filters-adapters4.trasformers filters-adapters
4.trasformers filters-adaptersxavazque2
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructorHaresh Jaiswal
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objectsMahmoud Alfarra
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionOUM SAOKOSAL
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202Mahmoud Samir Fayed
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesHitesh-Java
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objectsraksharao
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 

What's hot (20)

4.trasformers filters-adapters
4.trasformers filters-adapters4.trasformers filters-adapters
4.trasformers filters-adapters
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objects
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Java Day-1
Java Day-1Java Day-1
Java Day-1
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
Oop
OopOop
Oop
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
 
Java
JavaJava
Java
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 

Similar to Core Java Programming Language (JSE) : Chapter VI - Class Design

Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Chris Tankersley
 
Learn java
Learn javaLearn java
Learn javaPalahuja
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Advance unittest
Advance unittestAdvance unittest
Advance unittestReza Arbabi
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptxRaazIndia
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxKunalYadav65140
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
 
Core Java Programming Language (JSE) : Chapter VII - Advanced Class Features
Core Java Programming Language (JSE) : Chapter VII - Advanced Class FeaturesCore Java Programming Language (JSE) : Chapter VII - Advanced Class Features
Core Java Programming Language (JSE) : Chapter VII - Advanced Class FeaturesWebStackAcademy
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Manykenatmxm
 

Similar to Core Java Programming Language (JSE) : Chapter VI - Class Design (20)

Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016
 
Learn java
Learn javaLearn java
Learn java
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Only oop
Only oopOnly oop
Only oop
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
 
Advance unittest
Advance unittestAdvance unittest
Advance unittest
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptx
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptx
 
2java Oop
2java Oop2java Oop
2java Oop
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Core Java Programming Language (JSE) : Chapter VII - Advanced Class Features
Core Java Programming Language (JSE) : Chapter VII - Advanced Class FeaturesCore Java Programming Language (JSE) : Chapter VII - Advanced Class Features
Core Java Programming Language (JSE) : Chapter VII - Advanced Class Features
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Java
JavaJava
Java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 

More from WebStackAcademy

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesWebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online PortfolioWebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career RoadmapWebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationWebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationWebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - DirectivesWebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - IntroductionWebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging TechniquesWebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 

More from WebStackAcademy (20)

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 

Recently uploaded

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

Recently uploaded (20)

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

Core Java Programming Language (JSE) : Chapter VI - Class Design

  • 1. www.webstackacademy.com Java Programming Language SE – 6 Module 6 : Class Design
  • 2. www.webstackacademy.com Objectives ● Define inheritance, polymorphism, overloading, overriding, and virtual method invocation ● Use the access modifiers protected and the default (package-friendly) ● Describe the concepts of constructor and method overloading ● Describe the complete object construction and initialization operation
  • 3. www.webstackacademy.com Relevance ● How does the Java programming language support object inheritance?
  • 7. www.webstackacademy.com Single Inheritance ● When a class inherits from only one class, it is called single inheritance. ● Interfaces provide the benefits of multiple inheritance without drawbacks. ● Syntax of a Java class is as follows: <modifier> class <name> [extends <superclass>] { <declaration>* }
  • 9. www.webstackacademy.com Access Control ● Access modifiers on class member declarations are listed here.
  • 10. www.webstackacademy.com Overriding Methods ● A subclass can modify behavior inherited from a parent class. ● A subclass can create a method with different functionality than the parent’s method but with the same: – Name – Return type – Argument list
  • 11. www.webstackacademy.com Overriding Methods public class Employee { protected String name; protected double salary; protected Date birthDate; Public String getDetails(){ Return “Name:”+name+”n”+”Salary:”+salary; } }
  • 12. www.webstackacademy.com Overriding Methods public class Manager extends Employee { protected String department; public String getDetails() { return “Name: “ + name + “n” + “Salary: “ + salary +”n” +”Manager of:”+ department; } }
  • 13. www.webstackacademy.com Rules of Method Overriding Overridden methods can't be less accessible. public class Parent { public void doSomething() {} } public class Child extends Parent { private void doSomething() {} // illegal }
  • 14. www.webstackacademy.com Invoking Overridden Methods A subclass method may invoke a superclass method using the super keyword: ● The keyword super is used in a class to refer to its superclass. ● The keyword super is used to refer to the members of superclass, both data attributes and methods. ● Behavior invoked does not have to be in the superclass; it can be further up in the hierarchy.
  • 15. www.webstackacademy.com Invoking Overridden Methods public class Employee { protected String name; protected double salary; protected Date birthDate; public String getDetails(){ return “Name:”+name+”n”+”Salary:”+salary; } }
  • 16. www.webstackacademy.com Invoking Overridden Methods public class Manager extends Employee { protected String department; public String getDetails() { //call parent method return super.getDetails()+”nDepartment:”+ department; } }
  • 17. www.webstackacademy.com Polymorphism ● Polymorphism is the ability to have many different forms; for example, the Manager class has access to methods from Employee class. ● An object has only one form. ● A reference variable can refer to objects of different forms.
  • 19. www.webstackacademy.com Polymorphism Employee e = new Manager(); // legal // illegal attempt to assign Manager attribute e.department = "Sales"; // the variable is declared as an Employee type, // even though the Manager object has that attribute
  • 20. www.webstackacademy.com Virtual Method Invocation ● Virtual method invocation is performed as follows: Employee e = new Manager(); e.getDetails(); ● Compile-time type and runtime type invocations have the following characteristics: ● The method name must be a member of the declared variable type; in this case Employee has a method called getDetails. ● The method implementation used is based on the runtime object’s type; in this case the Manager class has an implementation of the getDetails method.
  • 21. www.webstackacademy.com Homogeneous Collections ● Collections of objects with the same class type are called homogeneous collections. For example: MyDate[] dates = new MyDate[2]; dates[0] = new MyDate(22, 12, 1964); dates[1] = new MyDate(22, 7, 1964);
  • 22. www.webstackacademy.com Heterogeneous Collections ● Collections of objects with different class types are called heterogeneous collections. For example: Employee [] staff = new Employee[1024]; staff[0]= new Manager(); staff[1]= new Employee(); staff[2]= new Engineer();
  • 23. www.webstackacademy.com Polymorphic Arguments Because a Manager is an Employee, the following is valid: public class TaxService { public TaxRate findTaxRate(Employee e) { // calculate the employee’s tax rate }} // Meanwhile, elsewhere in the application class TaxService taxSvc = new TaxService(); Manager m = new Manager(); TaxRate t = taxSvc.findTaxRate(m);
  • 24. www.webstackacademy.com The instanceof Operator public class Employee extends Object public class Manager extends Employee public class Engineer extends Employee ---------------------------------------- public void doSomething(Employee e) { if ( e instanceof Manager ) { // Process a Manager } else if ( e instanceof Engineer ) { // Process an Engineer } else { // Process any other type of Employee }}
  • 25. www.webstackacademy.com Casting Objects public void doSomething(Employee e) { if ( e instanceof Manager ) { Manager m = (Manager) e; System.out.println(“This is the manager of ” + m.getDepartment()); } // rest of operation }
  • 26. www.webstackacademy.com Casting Objects ● Use instanceof to test the type of an object. ● Restore full functionality of an object by casting. ● Check for proper casting using the following guidelines: ● Casts upward in the hierarchy are done implicitly. ● Downward casts must be to a subclass and checked by the compiler. ● The object type is checked at runtime when runtime errors can occur.
  • 27. www.webstackacademy.com Overloading Methods ● Use overloading as follows: – public void println(int i) – public void println(float f) – public void println(String s) ● Argument lists must differ. ● Return types can be different.
  • 28. www.webstackacademy.com Methods Using Variable Arguments public float average(int... nums) { int sum = 0; for ( int x : nums ) { sum += x; } return ((float) sum) / nums.length; } ● The vararg parameter is treated as an array. For ● Example: float gradePointAverage = stats.average(4, 3, 4);
  • 29. www.webstackacademy.com Overloading Constructors ● As with methods, constructors can be overloaded. An example is: public Employee(String name, double salary, Date DoB) public Employee(String name, double salary) public Employee(String name, Date DoB) ● Argument lists must differ. ● You can use the this reference at the first line of a constructor to call another constructor.
  • 30. www.webstackacademy.com Constructors Are Not Inherited ● A subclass inherits all methods and variables from the superclass (parent class). ● A subclass does not inherit the constructor from the superclass. • Two ways to include a constructor are: • Use the default constructor. • Write one or more explicit constructors.
  • 31. www.webstackacademy.com Invoking Parent Class Constructors ● To invoke a parent constructor, you must place a call to super in the first line of the constructor. ● You can call a specific parent constructor by the arguments that you use in the call to super. ● If no this or super call is used in a constructor, then the compiler adds an implicit call to super() that calls the parent no argument constructor (which could be the default constructor). If the parent class defines constructors, but does not provide a no- argument constructor, then a compiler error message is issued.
  • 32. www.webstackacademy.com The Object Class ● The Object class is the root of all classes in Java. ● A class declaration with no extends clause implies extends Object. For example: public class Employee { ... } is equivalent to: public class Employee extends Object { ... }
  • 33. www.webstackacademy.com The Object Class ● Two important methods are: – equals – toString
  • 34. www.webstackacademy.com The equals Method ● The == operator determines if two references are identical to each other (that is, refer to the same object). ● The equals method determines if objects are equal but not necessarily identical. ● The Object implementation of the equals method uses the == operator. ● User classes can override the equals method to implement a domain- specific test for equality. ● Note: You should override the hashCode method if you override the equals method.
  • 35. www.webstackacademy.com An equals Example-1 public class MyDate { private int day; private int month; private int year; public MyDate(int day, int month, int year) { this.day= day; this.month = month; this.year = year; }
  • 36. www.webstackacademy.com An equals Example-1 public boolean equals(Object o) { boolean result = false; if ( (o != null) && (o instanceof MyDate) ) { MyDate d = (MyDate) o; if ( (day == d.day) && (month == d.month) && (year == d.year) ) { result = true; }} return result; } public int hashCode() { return (day ^ month ^ year); }}
  • 37. www.webstackacademy.com An equals Example-2 class TestEquals { public static void main(String[] args) { MyDate date1 = new MyDate(14, 3, 1976); MyDate date2 = new MyDate(14, 3, 1976); if ( date1 == date2 ) { System.out.println("date1 is identical to date2"); } else { System.out.println("date1 is not identical to date2"); } if ( date1.equals(date2) ) { System.out.println("date1 is equal to date2"); } else { System.out.println("date1 is not equal to date2"); }
  • 38. www.webstackacademy.com An equals Example-2 System.out.println("set date2 = date1;"); date2 = date1; if ( date1 == date2 ) { System.out.println("date1 is identical to date2"); } else { System.out.println("date1 is not identical to date2"); }}}
  • 39. www.webstackacademy.com The toString Method The toString method has the following characteristics: ● This method converts an object to a String. ● Use this method during string concatenation. ● Override this method to provide information about a user-defined object in readable format. ● Use the wrapper class’s toString static method to convert primitive types to a String.
  • 40. www.webstackacademy.com Wrapper Classes Look at primitive data elements as objects.
  • 41. www.webstackacademy.com Wrapper Classes ● An example of a wrapper class is: int pInt = 420; Integer wInt = new Integer(pInt); // this is called boxing int p2 = wInt.intValue(); // this is called unboxing ● Other methods are: int x = Integer.valueOf(str).intValue(); int x = Integer.parseInt(str);
  • 42. www.webstackacademy.com Autoboxing of Primitive Types Autoboxing has the following description: • Conversion of primitive types to the object equivalent • Wrapper classes not always needed • Example: int pInt = 420; Integer wInt = pInt; // this is called autoboxing int p2 = wInt; // this is called autounboxing • Language feature used most often when dealing with collections • Wrapped primitives also usable in arithmetic expressions • Performance loss when using autoboxing
  • 43. www.webstackacademy.com Web Stack Academy (P) Ltd #83, Farah Towers, 1st floor,MG Road, Bangalore – 560001 M: +91-80-4128 9576 T: +91-98862 69112 E: info@www.webstackacademy.com