This document provides an overview and agenda for a Java introduction presentation. It covers topics like the types of programming languages, what Java is and why it was developed, how to set up your environment to write Java programs, the basics of the Java language including variables, types, operators, methods, conditionals, loops, arrays, and object-oriented programming concepts. It also discusses how to write a first simple Java program and solve problems using Java.
In this chapter we will review how to work with text files in C#. We will explain what a stream is, what its purpose is, and how to use it. We will explain what a text file is and how can you read and write data to a text file and how to deal with different character encodings. We will demonstrate and explain the good practices for exception handling when working with files. All of this will be demonstrated with many examples in this chapter
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
Here we are going to take a look how to use for loop, foreach loop and while loop. Also we are going to learn how to use and invoke methods and how to define classes in Java programming language.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
19. Data Structures and Algorithm ComplexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use. We will explain how to choose between data structures like hash-tables, arrays, dynamic arrays and sets implemented by hash-tables or balanced trees. Almost all of these structures are implemented as part of NET Framework, so to be able to write efficient and reliable code we have to learn to apply the most appropriate structures for each situation.
In this chapter we will review how to work with text files in C#. We will explain what a stream is, what its purpose is, and how to use it. We will explain what a text file is and how can you read and write data to a text file and how to deal with different character encodings. We will demonstrate and explain the good practices for exception handling when working with files. All of this will be demonstrated with many examples in this chapter
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
Here we are going to take a look how to use for loop, foreach loop and while loop. Also we are going to learn how to use and invoke methods and how to define classes in Java programming language.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
19. Data Structures and Algorithm ComplexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use. We will explain how to choose between data structures like hash-tables, arrays, dynamic arrays and sets implemented by hash-tables or balanced trees. Almost all of these structures are implemented as part of NET Framework, so to be able to write efficient and reliable code we have to learn to apply the most appropriate structures for each situation.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
In this chapter we will explore strings. We are going to explain how they are implemented in Java and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions.
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
In this chapter we will examine the loop programming constructs through which we can execute a code snippet repeatedly. We will discuss how to implement conditional repetitions (while and do-while loops) and how to work with for-loops. We will give examples of different possibilities to define loops, how to construct them and some of their key usages. Finally, we will discuss the foreach-loop construct and how we can use multiple loops placed inside each other (nested loops).
What is Data Type?
Primitive Types in C#: Integer Types, Floating-Point Types, Decimal Type, Boolean Type, Character Types, Strings, Objects
Value Types and Reference Types
Variables. Using Variables: Declaring, Initializing, Assigning Value, Accessing Value
Literals: The Values of the Variables in the Source Code. Boolean Literals. Integer Literals. Floating-Point Literals, Decimal Literals, String Literals and Escaping Sequences
Exercises: Working with Primitive Types and Variables
19. Java data structures algorithms and complexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use.
In this chapter we will explore strings. We are going to explain how they are implemented in C# and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions. We will discuss some classes for efficient construction of strings. Finally, we will take a look at the methods and classes for achieving more elegant and stricter formatting of the text content.
Chapter 22. Lambda Expressions and LINQIntro C# Book
In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
In this chapter we will explore strings. We are going to explain how they are implemented in Java and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions.
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
In this chapter we will examine the loop programming constructs through which we can execute a code snippet repeatedly. We will discuss how to implement conditional repetitions (while and do-while loops) and how to work with for-loops. We will give examples of different possibilities to define loops, how to construct them and some of their key usages. Finally, we will discuss the foreach-loop construct and how we can use multiple loops placed inside each other (nested loops).
What is Data Type?
Primitive Types in C#: Integer Types, Floating-Point Types, Decimal Type, Boolean Type, Character Types, Strings, Objects
Value Types and Reference Types
Variables. Using Variables: Declaring, Initializing, Assigning Value, Accessing Value
Literals: The Values of the Variables in the Source Code. Boolean Literals. Integer Literals. Floating-Point Literals, Decimal Literals, String Literals and Escaping Sequences
Exercises: Working with Primitive Types and Variables
19. Java data structures algorithms and complexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use.
In this chapter we will explore strings. We are going to explain how they are implemented in C# and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions. We will discuss some classes for efficient construction of strings. Finally, we will take a look at the methods and classes for achieving more elegant and stricter formatting of the text content.
Chapter 22. Lambda Expressions and LINQIntro C# Book
In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
Technical operations is plagued with an unhealthy infatuation of typically untested, imperative code with a high reliance on shared mutable state using dynamically typed languages such as Ruby, Python, Bash, and - ugh - remember Perl? :) In an age where building reliable infrastructure to elastically scale applications and services are paramount to business success, we need to start rethinking the infrastructure engineer’s toolkit and guiding principles. This talk will take a look at applying various functional techniques to building and automating infrastructure. From functional package management and congruent configuration to declarative cloud provisioning we’ll see just how practical these techniques typically used in functional programming for applications can be used to help build more robust and predictable infrastructures. While specific code examples will be given, the emphasis of the talk will be on guiding principles and functional design.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
2. Agenda
• Overview of Programming Languages.
• What’s and why Java.
• What’s Eclipse .
• Writing first program in Java.
• Basics of java programming Language.
• Variables, Operators and Types.
• Methods, Conditionals and Loops.
3. Agenda cont.
• Classes, Arrays and objects.
• Solving a problems in Java.
• Object-oriented Programming(OOP).
• Inheritance.
4. Overview of Programming Languages.
• There are three types of programming
languages:
Machine Languages that encoded in 1’s and 0’s,
that’s hard to write program in these languages.
Low Level Languages(e.g. Assembly)it’s close to
the machine code but not the same also it’s easer
to write and read(understand).
High Level Languages (e.g. C,C++,Java and
C#)these Languages needs a compiler to
translate the program into machine code.
5. What’s Java
• Java is an OOP language developed at Sun
Microsystems Labs by James Gosling at 1991.
• The first version called “OAK” but at 1995
“Netscape” announced that Java would be
incorporated into Netscape Navigator.
• Sun formally announced Java at a major
conference in May 1995.
• it is also a good not only in “object-oriented
programming “but also in “general programming
language”.
6. Why Java
• Java has some advantages make it differ
from the other languages as:
o That it is platform independent(mean work well in the internet). It
achieves this by using something called the ‘Java Virtual Machine’
(JVM).
o It’s a free source language.
8. What’s Eclipse
• Eclipse is a portable IDE for java it’s easy and
powerful.
• There are more than one IDE for java as
NetBeans, JBuilder and JDeveloper.
9. Prepare your PC and yourself!
• First you must download JDK from sun or go
to here.
• Then run the IDE that you will treat with it
here we will work by Eclipse.
• To download Eclipse IDE go to here or go to
the home page of Eclipse .
• Just you download the IDE (hint: Eclipse is portable not installed)
run it that will Explained by video.
10. The first program in java
• Write the program:
public class FirstProgram
{
public static void main (String[] args)
{
System.out.print("Hello, 2 + 3 = ");
System.out.println(5);
System.out.println("Good Bye");
}
}
11. Basics of Java
• Program Structure
class CLASSNAME {
public static void main(String[] args)
{
STATEMENTS
}
}
12. Variables
• Named location that stores a value
• Form:
TYPE NAME;
• Example:
String fName;
class Hello {
public static void main(String[] arguments)
{
String fName = “ragab”;
System.out.println(fName);
fName = "Something else";
System.out.println(fName);
}
}
13. Types
• Limits a variable to kinds of values
String: plain text (“hello”)
double: Floating-point, “real” valued
number(3.14, -7.0)
int: integer (5, -18)
String fName = “hello”;
double Pi = 3.14;
14. Types
• Order of Operations :Precedence like math, left
to right.
Right hand side of = evaluated first.
double x= 20
double x =3 / 2+ 1; // x= 2.0
• Conversion by casting
Int a = 2; // a = 2
double a = (double)2; // a = 2.0
double a = 2/3; // a = 0.0
double a = (double)2/3; // a = 0.6666…
int a = (int)18.7; // a=18
15. Types
• Conversion by method:
o Int to String:
String five = Integer.toString(5);
String five = “” + 5; // five = “5”
o String to int:
Int a=Integer.parseInt(“18”);
• Mathematical Functions:
o Math.sin(x)
o Math.cos(Math.PI / 2)
o Math.log(Math.log(x + y))
17. Example
class Math {
public static void main(String[] arguments)
{
int score;
score = 1 + 2 * 3;
System.out.println(score);
double copy = score;
copy = copy / 2;
System.out.println(copy);
score = (int) copy;
System.out.println(score);
}
}
18. Methods
• Adding Methods
public static void NAME() { STATEMENTS }
• To call a method:
NAME();
• Parameters
public static void NAME(TYPE NAME) { STATEMENTS }
• To call:
NAME(EXPRESSION);
19. Methods
• Example:
class Square {
Public static void printSquare(int x){
System.out.println(x*x);}
public static void main(String[] arguments){
int value = 2;
printSquare(value);
printSquare(3);
printSquare(value*22);
}
}
20. Methods
• Multiple Parameters
*…+ NAME(TYPE NAME, TYPE NAME) {STATEMENTS }
NAME(arg1, arg2);
• Return Values
public static TYPE NAME() {
STATEMENTS
return EXPRESSION;
}
void means “no type”
21. Conditionals
• if statement
if (COMPARISON) {STATEMENTS }
• Example:
class If {
public static void test((int x)) {
if (x > 5){
System.out.println((x + " is > 5");
}
}
public static void main(String[] arguments){
test(6);
test(5);
test(4);
}
}
22. Conditionals
• Comparison operators
x > y: x is greater than y
x< y: x is less than y
x >= y: x is greater than or equal to y
x <= y: x is less than or equal to y
x == y: x equals y (assignment: =)
23. Conditionals
• else
if (COMPARISON) {STATEMENTS
} else {
STATEMENTS
}
• else if
if (COMPARISON) {STATEMENTS
} else if (COMPARISON) { STATEMENTS
} else if (COMPARISON) { STATEMENTS
}
else {
STATEMENTS
}
24. Conditionals
• Example
public static void test(int x){
if (x > 5){
System.out.println(x + " is > 5");}
else if (x == 5){
System.out.println(x + " equals 5");}
else {
System.out.println(x +”is < 5"); -
}
public static void main(String[] arguments){
test(6);
test(5);
test(4);
}
25. Loops
static void main (String[] arguments) {
System.out.println(“This is line 1”);
System.out.println(“This is line 2”);
System.out.println(“This is line 3”);
}
• What if you want to do it for 200 lines?
• Loop operators allow to loop through a block
of code.
• There are several loop operators in Java.
26. Loops
• The while operator:
while (condition) {statement}
• Example:
int i = 0;
while (i < 3) {
System.out.println(“This is line “ + i);
i = i+1;}
• Count carefully
• Make sure that your loop has a chance to finish.
27. Loops
• The for operator:
for (initialization;condition;update){statement}
• Example:
int i;
for (i = 0; i < 3; i=i++) {
System.out.println (“This is line “ + i);}
• Embedded loops:
for (int i = 0; i < 3; i++) {
for (int j = 2; j < 4; j++){
System.out.println (i + “ “ + j);
} }
• Scope of the variable defined in the initialization:
respective for block
28. Loops
• Branching Statements :
• break terminates a for or while loop
for (int i=0; i<100; i++) {if(i ==
terminationValue)
break;
else {...}
}
• continue skips the current iteration of a for or while loop
and proceeds directly to the next iteration
for (int i=0; i<100; i++) {
if(i == skipValue)
continue;
else {...}
}
29. Arrays
• An array is an indexed list of values.
• You can make an array of int, of double, of
String,etc.All elements of an array must have
the same type.
0 1 2 3 n-1
• This array contain n elements.
30. Arrays
• An array is noted using [] and is declared in the
usual way:
int values[]; // empty array
int[] values; // equivalent declaration
• To create an array of a given size, use the
operator new :
int values[] = new int[5];
• or you may use a variable to specify the size:
int size = 12;
int values[] = new int[size];
31. Arrays
• Array Initialization:
• Curly braces can be used to initialize an array in
the array declaration statement (and only there).
int values[] = { 12, 24, -23, 47 };
• To access the elements of an array, use the []
operator: values[index]
• Example:
int values[] = { 12, 24, -23, 47 };
values[3] = 18; // write
int x = values[1] + 3; // read
32. Arrays
• Each array has a length variable built-in that contains the length of the array.
int values[] = new int[12];
int size = values.length; // 12
• Looping through an array
• Example :
int values[] = new int[5];
for (int i=0; i<values.length; i++) {
values[i] = i;
int y = values[i] *values[i];
System.out.println(y);
}
• Another one:
double values[] = new double[25];
int j=0;
while (j<values.length) {...
j++;
}
33. Objects
• Objects are a collection of related data and
methods.
• Example:
• Strings A string is a collection of characters
(letters) and has a set of methods built in.
String nextTrip = “Mexico”;
int size = nextTrip.length(); // 6
34. Objects
• To create a new object, use the new operator.
If you do not use new, you are making a
reference to an object (i.e. a pointer to the
same object).
Point p;
p.x = 23;
p.y = -12;
public static Point middlePoint (Point p1, Point p2) {
Point q = new Point ((p1.x+p2.x)/2, (p1.y+p2.y)/2);
return q; }
35. Classes
• A class is a prototype to design objects.
• It is a set of variables and methods that
encapsulates the properties of the class of
objects.
• In Java, you can (will) create several classes in
project.
• A class constructor is called each time an
object of the class is instantiated (created).
36. Packages
• A package is a set of classes that relate to a
same purpose.
• Example: math, graphics, input/output...
• In order to use a package, you have to import
it. package
class class class
object
37. Object Oriented Programming
• Objects are a collection of related data and
methods.
• To create a new object, use the new operator.
If you do not use new, you are making a
reference to an object (i.e a pointer to the
same object).
38. Objects and references
Point p1 = new Point (12,34);
Point p2 = p1;
System.out.println(“x = “ + p2.x); // 12
p1.x = 24;
System.out.println(“x = “ + p2.x); // 24!
39. The null object
• null simply represents no object. It is
convenient
• as a return value to mean that a method failed
for example. It may also be used to “remove”
an element from an array.
String values[] = { “ragab”, “ahmed”, “zidan” };
values[1] = null;
40. Object methods v.s. class methods
class Bicycle {
static int gear, speed;
public static void speedUp (Bicycle b) {
b.speed += 10;}
public static void main (String[] arguments) {
Bicycle bike1 = new Bicycle();
speedUp (bike1); }}
• static means that the variable is going to be same
for all objects of the class.
• Class methods are declared static.
• static = the same for all objects
• nonstatic = different for each object
41. Abstraction
• Objects are tools for abstraction.
• Abstraction is a fundamental concept in
computer science.
• In Java, objects are instances of a class.
• A class contains variables and methods that
capture the essence of the object.
• An object is instantiated using new
42. Why is abstraction important?
• Modularity (allows to subdivide a big problem
into smaller sub-problems)
• Powerful representation of real-world
problems
43. Inheritance
• In the world, people inherit characteristics
from their parents.
• In computer science, objects inherit variables
and methods from their parents.
• When you define a class in Java, you may
define it as a subclass of another class (its
parent).
44. Why inheritance and it’s rules?
• Avoid duplicate code
• Improve modularity
Inheritance rules
• The subclass inherits all variables and methods
• Use the extends keyword to indicate that one
class inherits from another
• Use the super keyword in the subclass
constructor to call the parent constructor
46. Example
public class Vehicle {
public int nWheels; // number of wheels
public Vehicle (int n)
{nWheels = n;}
int getNWheels ()
{return nWheels;}}
• ----------------------------------------
public class Car extends Vehicle {
public Car (int n)
{super (n);}
public void openWindow() {}
}
47. Example
public class Bicycle extends Vehicle {
public Bicycle (int n)
{super (n);}
public void freeStyle() {}
}
• -------------------------------------
public class World {
public static void main (String[] args) {
Bicycle bike = new Bike (2);
Car car = new Car (4);
System.out.println (“Car has “ +car.getNWheels() + “ wheels”);
System.out.println (“Bike has “ +bike.getNWheels() + “ wheels”);--
48. OOP: Scope & Visibility
• Scope:
– A variable cannot be used outside of
the curly braces (“,...-”) in which it is declared.
– E.g., Class-level variables (fields) are usable
everywhere in the class; loop variables are only
usable in the scope of the loop
49. OOP: Scope & Visibility
• Visibility:
– public fields, methods, & constructors can be “seen”
or used directly by all classes & subclasses
– protected fields, methods, & constructors can only
be seen or used from within their class or subclasses
– private fields, methods, & constructors can only be
seen or used from within their exact class (in general,
most or all of a class’s fields should be private)
– Fields, methods, and constructors with unspecified
(“default” or “package”) visibility can be seen by
some classes – more on this later
50. OOP: Getter & Setter Methods
• Another way to access or modify fields
• Good programming practice
• Widely-used convention in Java
• Also called accessors and mutators
• Don’t come for free, but very useful when
dealing with private or protected fields
51. OOP: Ecapsulation
• The Principle of Encapsulation
• Allows one to access and change the internals
of a class, without having “direct access”
• Visibility, Accessors, & Mutators are vital tools
for this OOP principle
52. OOP: this
• A way for an instance of class to refer to itself
– E.g.: say Engineer has a field called trafficHours and a
setter method with this signature:
– public void setTrafficHours(int trafficHours);
– How to resolve scope?
– Solution: use this.trafficHours = trafficHours;
– this does not work inside static methods
• Good programming practice
• Standard Java convention
• Does come for free, has many uses
53. Inheritance & Abstraction
• A class can extend another (single) class
• Subclasses inherit methods and variables from
their parents
• This allows us to use objects to form an
hierarchy of representations
• Classifications of objects and relationships
between them can now be modeled!
54. Inheritance & Abstraction:The Object
class
• Every class implicitly extends Object
• So, in Java, every object is an Object…
• “Class Object is the root of the class hierarchy.
Every class has Object as a superclass. All
objects, including arrays, implement the
methods of this class.” – from the Java API
• Core and backbone of OOP in Java
• Methods of note are equals(Object) and
toString() – more on these later
55. Inheritance & Abstraction:Overriding
& Overloading
• What if we want a subclass’s inherited method
to do something different than that of its
parent? – Override it!
• What if we want multiple constructors for a
class, or methods with the same name but
different arguments? – Overload them!
56. Inheritance & Abstraction:Overriding
& Overloading
• Overriding: re-defining an inherited method
• E.g., Say every Manager gets a weekly bonus
of amount weeklyBonus (which would be
defined somewhere in the class)
• To reflect this, we can override the
weeklyPay() method simply by explicitly
defining it again in Manager, with the desired
changes
57. Inheritance & Abstraction:Overriding
& Overloading
• Overloading: method or constructor with
same name and type as another, but with a
different signature (i.e., takes different
number, ordering, or types of arguments)
• Cannot have methods with same name and
arguments and different return type
58. Method Overriding
• Method overriding occurs when a subclass
implements a method that is already implemented in a
superclass. The method name must be the same, and
the parameter and return types of the subclass's
implementation must be subtypes of the superclass's
implementation. You cannot allow less access than the
access level of the superclass's method.
eg,
class Timer {
public Date getDate(Country c) { ... } }
class USATimer {
public Date getDate(USA usa) { ... } }
59. Method Overloading
• Method overloading is when two methods
share the same name but have a different
number or type of parameters.
eg,
public void print(String str) { ...
}
public void print(Date date) { ...
}
60. References
• Java how to program, book.
• Essential Java for scientists and Engineering,
book.
• MIT Lectures.
• Tutorial from sun.