SlideShare a Scribd company logo
UMBC CMSC 331 Java
JAVAJAVA
BASICSBASICS
UMBC CMSC 331 Java
Comments are almost like C++
The javadoc program generates HTML API documentation
from the “javadoc” style comments in your code.
/* This kind of comment can span multiple lines */
// This kind is to the end of the line
/**
* This kind of comment is a special
* ‘javadoc’ style comment
*/
UMBC CMSC 331 Java
An example of a class
class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name +
' is now ' + age);
}
}
Variable
Method
UMBC CMSC 331 Java
Scoping
• As in C/C++, scope is determined by the placement of curly braces {}.
• A variable defined within a scope is available only to the end of that
scope.
{ int x = 12;
/* only x available */
{ int q = 96;
/* both x and q available */
}
/* only x available */
/* q “out of scope” */
}
{ int x = 12;
{ int x = 96; /* illegal */
}
}
This is ok in C/C++ but not in Java.
UMBC CMSC 331 Java
An array is an object
• Person mary = new Person ( );
• int myArray[ ] = new int[5];
• int myArray[ ] = {1, 4, 9, 16, 25};
• String languages [ ] = {"Prolog",
"Java"};
• Since arrays are objects they are allocated dynamically
• Arrays, like all objects, are subject to garbage collection
when no more references remain
– so fewer memory leaks
– Java doesn’t have pointers!
UMBC CMSC 331 Java
Scope of Objects
• Java objects don’t have the same lifetimes as
primitives.
• When you create a Java object using new, it hangs
around past the end of the scope.
• Here, the scope of name s is delimited by the {}s
but the String object hangs around until GC’d
{
String s = new String("a string");
} /* end of scope */
UMBC CMSC 331 Java
Methods, arguments and return values
• Java methods are like C/C++ functions. General case:
returnType methodName ( arg1, arg2, … argN) {
methodBody
}
The return keyword exits a method optionally with a value
int storage(String s) {return s.length() * 2;}
boolean flag() { return true; }
float naturalLogBase() { return 2.718f; }
void nothing() { return; }
void nothing2() {}
UMBC CMSC 331 Java
The static keyword
• Java methods and variables can be declared static
• These exist independent of any object
• This means that a Class’s
– static methods can be called even if no objects of that
class have been created and
– static data is “shared” by all instances (i.e., one rvalue
per class instead of one per instance
class StaticTest {static int i = 47;}
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
// st1.i == st2.I == 47
StaticTest.i++; // or st1.I++ or st2.I++
// st1.i == st2.I == 48
UMBC CMSC 331 Java
Array Operations
• Subscripts always start at 0 as in C
• Subscript checking is done automatically
• Certain operations are defined on arrays of objects,
as for other classes
– e.g. myArray.length == 5
UMBC CMSC 331 Java
ExampleExample
ProgramsPrograms
Echo.java
C:UMBC331java>type echo.java
// This is the Echo example from the Sun tutorial
class echo {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
System.out.println( args[i] );
}
}
}
C:UMBC331java>javac echo.java
C:UMBC331java>java echo this is pretty silly
this
is
pretty
silly
C:UMBC331java>
UMBC CMSC 331 Java
Factorial Example
/**
* This program computes the factorial of a number
*/
public class Factorial { // Define a class
public static void main(String[] args) { // The program starts here
int input = Integer.parseInt(args[0]); // Get the user's input
double result = factorial(input); // Compute the factorial
System.out.println(result); // Print out the result
} // The main() method ends here
public static double factorial(int x) { // This method computes x!
if (x < 0) // Check for bad input
return 0.0; // if bad, return 0
double fact = 1.0; // Begin with an initial value
while(x > 1) { // Loop until x equals 1
fact = fact * x; // multiply by x each time
x = x - 1; // and then decrement x
} // Jump back to the star of loop
return fact; // Return the result
} // factorial() ends here
} // The class ends here
From Java in a Nutshell
UMBC CMSC 331 Java
JAVA Classes
• The class is the fundamental concept in JAVA (and other
OOPLs)
• A class describes some data object(s), and the operations
(or methods) that can be applied to those objects
• Every object and method in Java belongs to a class
• Classes have data (fields) and code (methods) and classes
(member classes or inner classes)
• Static methods and fields belong to the class itself
• Others belong to instances
UMBC CMSC 331 Java
Example
public class Circle {
// A class field
public static final double PI= 3.14159; // A useful constant
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads * 180 / PI;
}
// An instance field
public double r; // The radius of the circle
// Two methods which operate on the instance fields of an object
public double area() { // Compute the area of the
circle
return PI * r * r;
}
public double circumference() { // Compute the circumference of
the circle
return 2 * PI * r;
}
}
UMBC CMSC 331 Java
Constructors
• Classes should define one or more methods to create or
construct instances of the class
• Their name is the same as the class name
– note deviation from convention that methods begin with lower case
• Constructors are differentiated by the number and types of
their arguments
– An example of overloading
• If you don’t define a constructor, a default one will be
created.
• Constructors automatically invoke the zero argument
constructor of their superclass when they begin (note that
this yields a recursive process!)
UMBC CMSC 331 Java
Constructor example
public class Circle {
public static final double PI = 3.14159; // A constant
public double r; // instance field holds circle’s radius
// The constructor method: initialize the radius field
public Circle(double r) { this.r = r; }
// Constructor to use if no arguments
public Circle() { r = 1.0; }
// better: public Circle() { this(1.0); }
// The instance methods: compute values based on radius
public double circumference() { return 2 * PI * r; }
public double area() { return PI * r*r; }
}
this.r refers to the r
field of the class
This() refers to a
constructor for the class
UMBC CMSC 331 Java
Extending a class
• Class hierarchies reflect subclass-superclass relations among
classes.
• One arranges classes in hierarchies:
– A class inherits instance variables and instance methods from all of its
superclasses. Tree -> BinaryTree -> BST
– You can specify only ONE superclass for any class.
• When a subclass-superclass chain contains multiple instance
methods with the same signature (name, arity, and argument
types), the one closest to the target instance in the subclass-
superclass chain is the one executed.
– All others are shadowed/overridden.
• Something like multiple inheritance can be done via interfaces
(more on this later)
• What’s the superclass of a class defined without an extends
clause?
UMBC CMSC 331 Java
Extending a class
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r); // Invoke the constructor of the superclass, Circle()
this.cx = x; // Initialize the instance field cx
this.cy = y; // Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy; // Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r); // Returns true or false
}
}
UMBC CMSC 331 Java
Overloading, overwriting, and shadowing
• Overloading occurs when Java can distinguish two procedures with the
same name by examining the number or types of their parameters.
• Shadowing or overriding occurs when two procedures with the same
signature (name, the same number of parameters, and the same
parameter types) are defined in different classes, one of which is a
superclass of the other.
UMBC CMSC 331 Java
On designing class hierarchies
• Programs should obey the explicit-representation principle, with classes
included to reflect natural categories.
• Programs should obey the no-duplication principle, with instance methods
situated among class definitions to facilitate sharing.
• Programs should obey the look-it-up principle, with class definitions
including instance variables for stable, frequently requested information.
• Programs should obey the need-to-know principle, with public interfaces
designed to restrict instance-variable and instance-method access, thus
facilitating the improvement and maintenance of nonpublic program
elements.
• If you find yourself using the phrase an X is a Y when describing the
relation between two classes, then the X class is a subclass of the Y class.
• If you find yourself using X has a Y when describing the relation between
two classes, then instances of the Y class appear as parts of instances of the
X class.
UMBC CMSC 331 Java
Data hiding and encapsulation
• Data-hiding or encapsulation is an important part
of the OO paradigm.
• Classes should carefully control access to their data
and methods in order to
– Hide the irrelevant implementation-level details so they
can be easily changed
– Protect the class against accidental or malicious damage.
– Keep the externally visible class simple and easy to
document
• Java has a simple access control mechanism to help
with encapsulation
– Modifiers: public, protected, private, and package
(default)
UMBC CMSC 331 Java
Example
encapsulation
package shapes; // Specify a package for the class
public class Circle { // The class is still public
public static final double PI = 3.14159;
protected double r; // Radius is hidden, but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
// The constructor method
public Circle(double r) {checkRadius(r); this.r = r; }
// Public data accessor methods
public double getRadius() { return r; };
public void setRadius(double r) { checkRadius(r); this.r = r;}
// Methods to operate on the instance field
public double area() { return PI * r * r; }
public double circumference() { return 2 * PI * r; }
}
UMBC CMSC 331 Java
Access control
• Access to packages
– Java offers no control mechanisms for packages.
– If you can find and read the package you can access it
• Access to classes
– All top level classes in package P are accessible
anywhere in P
– All public top-level classes in P are accessible anywhere
• Access to class members (in class C in package P)
– Public: accessible anywhere C is accessible
– Protected: accessible in P and to any of C’s subclasses
– Private: only accessible within class C
– Package: only accessible in P (the default)
UMBC CMSC 331 Java
UMBC CMSC 331 Java
Getters and setters
• A getter is a method that extracts information from an instance.
– One benefit: you can include additional computation in a getter.
• A setter is a method that inserts information into an instance (also
known as mutators).
– A setter method can check the validity of the new value (e.g., between 1
and 7) or trigger a side effect (e.g., update a display)
• Getters and setters can be used even without underlying matching
variables
• Considered good OO practice
• Essential to javabeans
• Convention: for variable fooBar of type fbtype, define
– getFooBar()
– setFooBar(fbtype x)
UMBC CMSC 331 Java
Example
getters and setters
package shapes; // Specify a package for the class
public class Circle { // The class is still public
// This is a generally useful constant, so we keep it public
public static final double PI = 3.14159;
protected double r; // Radius is hidden, but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
// The constructor method
public Circle(double r) { checkRadius(r); this.r = r;}
// Public data accessor methods
public double getRadius() { return r; };
public void setRadius(double r) { checkRadius(r); this.r = r;}
// Methods to operate on the instance field
public double area() { return PI * r * r; }
public double circumference() { return 2 * PI * r; }
}
UMBC CMSC 331 Java
Abstract classes and methods
• Abstract vs. concrete classes
• Abstract classes can not be instantiated
public abstract class shape { }
• An abstract method is a method w/o a body
public abstract double area();
• (Only) Abstract classes can have abstract methods
• In fact, any class with an abstract method is
automatically an abstract class
UMBC CMSC 331 Java
Example
abstract class
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference();// semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class Rectangle extends Shape {
protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods.
}
UMBC CMSC 331 Java
Syntax Notes
• No global variables
– class variables and methods may be applied to any
instance of an object
– methods may have local (private?) variables
• No pointers
– but complex data objects are “referenced”
• Other parts of Java are borrowed from PL/I,
Modula, and other languages

More Related Content

What's hot

Core java
Core javaCore java
Core java
Rajkattamuri
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
javeed_mhd
 
02 java basics
02 java basics02 java basics
02 java basics
bsnl007
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
laratechnologies
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
GaneshKumarKanthiah
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
JAINAM KAPADIYA
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
suraj pandey
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
rajkamaltibacademy
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
Abdii Rashid
 

What's hot (20)

Core java
Core javaCore java
Core java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
02 java basics
02 java basics02 java basics
02 java basics
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 

Viewers also liked

The Emergence of the “Church history” and the predicament of Orthodox Hierarc...
The Emergence of the “Church history” and the predicament of Orthodox Hierarc...The Emergence of the “Church history” and the predicament of Orthodox Hierarc...
The Emergence of the “Church history” and the predicament of Orthodox Hierarc...
Евгений Лютько
 
Podemos
PodemosPodemos
Ecologically sustainable planning
Ecologically sustainable planningEcologically sustainable planning
Ecologically sustainable planningSnigdha Jain
 
Renaissance Nature - ft2acres.com
Renaissance Nature -  ft2acres.comRenaissance Nature -  ft2acres.com
Renaissance Nature - ft2acres.com
Kin Housing
 
Dia de la madre
Dia de la madreDia de la madre
Dia de la madremeulaliafg
 
Spend a bit listen a lot - Playing with SDRs
Spend a bit listen a lot - Playing with SDRsSpend a bit listen a lot - Playing with SDRs
Spend a bit listen a lot - Playing with SDRs
Carlos Garcia Sanchez
 
contaminacion
contaminacioncontaminacion
contaminacion
3048919
 
Antonio Ruiz Suicide Silence
Antonio  Ruiz    Suicide  SilenceAntonio  Ruiz    Suicide  Silence
Antonio Ruiz Suicide Silenceguestd69a09
 
Securing the infrastructure using IDS
Securing the infrastructure using IDSSecuring the infrastructure using IDS
Securing the infrastructure using IDS
Ruban Deventhiran
 
Individual final assessment
Individual final assessmentIndividual final assessment
Individual final assessment
Patricia Sánchez Lamas
 
Dalla Bullet theory alla sociologia funzionalista dei media
Dalla Bullet theory alla sociologia funzionalista dei mediaDalla Bullet theory alla sociologia funzionalista dei media
Dalla Bullet theory alla sociologia funzionalista dei mediaDavide Bennato
 
Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...
Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...
Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...
Игорь Шадеркин
 
Teoria critica e teoria culturologica
Teoria critica e teoria culturologicaTeoria critica e teoria culturologica
Teoria critica e teoria culturologicaDavide Bennato
 
Números inteiros relativos adição e subtração
Números inteiros relativos   adição e subtraçãoNúmeros inteiros relativos   adição e subtração
Números inteiros relativos adição e subtração
PatriciaLavos
 

Viewers also liked (16)

The Emergence of the “Church history” and the predicament of Orthodox Hierarc...
The Emergence of the “Church history” and the predicament of Orthodox Hierarc...The Emergence of the “Church history” and the predicament of Orthodox Hierarc...
The Emergence of the “Church history” and the predicament of Orthodox Hierarc...
 
Podemos
PodemosPodemos
Podemos
 
Ecologically sustainable planning
Ecologically sustainable planningEcologically sustainable planning
Ecologically sustainable planning
 
Renaissance Nature - ft2acres.com
Renaissance Nature -  ft2acres.comRenaissance Nature -  ft2acres.com
Renaissance Nature - ft2acres.com
 
Dia de la madre
Dia de la madreDia de la madre
Dia de la madre
 
Spend a bit listen a lot - Playing with SDRs
Spend a bit listen a lot - Playing with SDRsSpend a bit listen a lot - Playing with SDRs
Spend a bit listen a lot - Playing with SDRs
 
contaminacion
contaminacioncontaminacion
contaminacion
 
Antonio Ruiz Suicide Silence
Antonio  Ruiz    Suicide  SilenceAntonio  Ruiz    Suicide  Silence
Antonio Ruiz Suicide Silence
 
28.DSCE_ESCO
28.DSCE_ESCO28.DSCE_ESCO
28.DSCE_ESCO
 
Ahmad-CCNP
Ahmad-CCNPAhmad-CCNP
Ahmad-CCNP
 
Securing the infrastructure using IDS
Securing the infrastructure using IDSSecuring the infrastructure using IDS
Securing the infrastructure using IDS
 
Individual final assessment
Individual final assessmentIndividual final assessment
Individual final assessment
 
Dalla Bullet theory alla sociologia funzionalista dei media
Dalla Bullet theory alla sociologia funzionalista dei mediaDalla Bullet theory alla sociologia funzionalista dei media
Dalla Bullet theory alla sociologia funzionalista dei media
 
Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...
Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...
Современный подход к подготовке врача-уролога: от «образования на всю жизнь» ...
 
Teoria critica e teoria culturologica
Teoria critica e teoria culturologicaTeoria critica e teoria culturologica
Teoria critica e teoria culturologica
 
Números inteiros relativos adição e subtração
Números inteiros relativos   adição e subtraçãoNúmeros inteiros relativos   adição e subtração
Números inteiros relativos adição e subtração
 

Similar to Java basic tutorial

Java Concepts
Java ConceptsJava Concepts
Java Concepts
AbdulImrankhan7
 
Core Java
Core JavaCore Java
Core Java
Khasim Saheb
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
mdfkhan625
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
Jacob William
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
shubhra chauhan
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
quantumiq448
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem4
 
3java Advanced Oop
3java Advanced Oop3java Advanced Oop
3java Advanced OopAdil Jafri
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
Java
JavaJava
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
SivaSankari36
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
Purvik Rana
 

Similar to Java basic tutorial (20)

Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Core Java
Core JavaCore Java
Core Java
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Inheritance
InheritanceInheritance
Inheritance
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
3java Advanced Oop
3java Advanced Oop3java Advanced Oop
3java Advanced Oop
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Java
JavaJava
Java
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 

More from Bui Kiet

Asynchronous javascript and xml
Asynchronous javascript and xmlAsynchronous javascript and xml
Asynchronous javascript and xml
Bui Kiet
 
Jquery tutorial
Jquery tutorialJquery tutorial
Jquery tutorial
Bui Kiet
 
Real time data integration best practices and architecture
Real time data integration best practices and architectureReal time data integration best practices and architecture
Real time data integration best practices and architecture
Bui Kiet
 
Jms introduction
Jms introductionJms introduction
Jms introduction
Bui Kiet
 
Wso2 in action
Wso2 in actionWso2 in action
Wso2 in action
Bui Kiet
 
Easy javascript
Easy javascriptEasy javascript
Easy javascript
Bui Kiet
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Technology presentations
Technology presentationsTechnology presentations
Technology presentations
Bui Kiet
 
Soap In Mule
Soap In MuleSoap In Mule
Soap In Mule
Bui Kiet
 
Mule Esb Batch process
Mule Esb Batch processMule Esb Batch process
Mule Esb Batch process
Bui Kiet
 
Mule solutions for data integration
Mule solutions for data integrationMule solutions for data integration
Mule solutions for data integration
Bui Kiet
 
Mulesoft corporate template final
Mulesoft corporate template  final Mulesoft corporate template  final
Mulesoft corporate template final
Bui Kiet
 
Biztalk vs mulesoft
Biztalk vs mulesoft Biztalk vs mulesoft
Biztalk vs mulesoft
Bui Kiet
 
Mule Sap Integration
Mule Sap IntegrationMule Sap Integration
Mule Sap Integration
Bui Kiet
 
Why Mulesoft ?
Why Mulesoft ?Why Mulesoft ?
Why Mulesoft ?
Bui Kiet
 
Mule Integration Simplified
Mule Integration SimplifiedMule Integration Simplified
Mule Integration Simplified
Bui Kiet
 
Mule ESB
Mule ESBMule ESB
Mule ESB
Bui Kiet
 
Enjoy Munit with Mule
Enjoy Munit with MuleEnjoy Munit with Mule
Enjoy Munit with Mule
Bui Kiet
 
.Net architecture with mule soft
.Net architecture with mule soft.Net architecture with mule soft
.Net architecture with mule soft
Bui Kiet
 

More from Bui Kiet (20)

Asynchronous javascript and xml
Asynchronous javascript and xmlAsynchronous javascript and xml
Asynchronous javascript and xml
 
Jquery tutorial
Jquery tutorialJquery tutorial
Jquery tutorial
 
Real time data integration best practices and architecture
Real time data integration best practices and architectureReal time data integration best practices and architecture
Real time data integration best practices and architecture
 
Jms introduction
Jms introductionJms introduction
Jms introduction
 
Wso2 in action
Wso2 in actionWso2 in action
Wso2 in action
 
Easy javascript
Easy javascriptEasy javascript
Easy javascript
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Technology presentations
Technology presentationsTechnology presentations
Technology presentations
 
Soap In Mule
Soap In MuleSoap In Mule
Soap In Mule
 
Mule Esb Batch process
Mule Esb Batch processMule Esb Batch process
Mule Esb Batch process
 
Mule solutions for data integration
Mule solutions for data integrationMule solutions for data integration
Mule solutions for data integration
 
Mulesoft corporate template final
Mulesoft corporate template  final Mulesoft corporate template  final
Mulesoft corporate template final
 
Biztalk vs mulesoft
Biztalk vs mulesoft Biztalk vs mulesoft
Biztalk vs mulesoft
 
Mule Sap Integration
Mule Sap IntegrationMule Sap Integration
Mule Sap Integration
 
Why Mulesoft ?
Why Mulesoft ?Why Mulesoft ?
Why Mulesoft ?
 
Mule Integration Simplified
Mule Integration SimplifiedMule Integration Simplified
Mule Integration Simplified
 
Mule ESB
Mule ESBMule ESB
Mule ESB
 
Enjoy Munit with Mule
Enjoy Munit with MuleEnjoy Munit with Mule
Enjoy Munit with Mule
 
.Net architecture with mule soft
.Net architecture with mule soft.Net architecture with mule soft
.Net architecture with mule soft
 

Recently uploaded

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 

Java basic tutorial

  • 1. UMBC CMSC 331 Java JAVAJAVA BASICSBASICS
  • 2. UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the “javadoc” style comments in your code. /* This kind of comment can span multiple lines */ // This kind is to the end of the line /** * This kind of comment is a special * ‘javadoc’ style comment */
  • 3. UMBC CMSC 331 Java An example of a class class Person { String name; int age; void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } } Variable Method
  • 4. UMBC CMSC 331 Java Scoping • As in C/C++, scope is determined by the placement of curly braces {}. • A variable defined within a scope is available only to the end of that scope. { int x = 12; /* only x available */ { int q = 96; /* both x and q available */ } /* only x available */ /* q “out of scope” */ } { int x = 12; { int x = 96; /* illegal */ } } This is ok in C/C++ but not in Java.
  • 5. UMBC CMSC 331 Java An array is an object • Person mary = new Person ( ); • int myArray[ ] = new int[5]; • int myArray[ ] = {1, 4, 9, 16, 25}; • String languages [ ] = {"Prolog", "Java"}; • Since arrays are objects they are allocated dynamically • Arrays, like all objects, are subject to garbage collection when no more references remain – so fewer memory leaks – Java doesn’t have pointers!
  • 6. UMBC CMSC 331 Java Scope of Objects • Java objects don’t have the same lifetimes as primitives. • When you create a Java object using new, it hangs around past the end of the scope. • Here, the scope of name s is delimited by the {}s but the String object hangs around until GC’d { String s = new String("a string"); } /* end of scope */
  • 7. UMBC CMSC 331 Java Methods, arguments and return values • Java methods are like C/C++ functions. General case: returnType methodName ( arg1, arg2, … argN) { methodBody } The return keyword exits a method optionally with a value int storage(String s) {return s.length() * 2;} boolean flag() { return true; } float naturalLogBase() { return 2.718f; } void nothing() { return; } void nothing2() {}
  • 8. UMBC CMSC 331 Java The static keyword • Java methods and variables can be declared static • These exist independent of any object • This means that a Class’s – static methods can be called even if no objects of that class have been created and – static data is “shared” by all instances (i.e., one rvalue per class instead of one per instance class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.I == 47 StaticTest.i++; // or st1.I++ or st2.I++ // st1.i == st2.I == 48
  • 9. UMBC CMSC 331 Java Array Operations • Subscripts always start at 0 as in C • Subscript checking is done automatically • Certain operations are defined on arrays of objects, as for other classes – e.g. myArray.length == 5
  • 10. UMBC CMSC 331 Java ExampleExample ProgramsPrograms
  • 11. Echo.java C:UMBC331java>type echo.java // This is the Echo example from the Sun tutorial class echo { public static void main(String args[]) { for (int i=0; i < args.length; i++) { System.out.println( args[i] ); } } } C:UMBC331java>javac echo.java C:UMBC331java>java echo this is pretty silly this is pretty silly C:UMBC331java>
  • 12. UMBC CMSC 331 Java Factorial Example /** * This program computes the factorial of a number */ public class Factorial { // Define a class public static void main(String[] args) { // The program starts here int input = Integer.parseInt(args[0]); // Get the user's input double result = factorial(input); // Compute the factorial System.out.println(result); // Print out the result } // The main() method ends here public static double factorial(int x) { // This method computes x! if (x < 0) // Check for bad input return 0.0; // if bad, return 0 double fact = 1.0; // Begin with an initial value while(x > 1) { // Loop until x equals 1 fact = fact * x; // multiply by x each time x = x - 1; // and then decrement x } // Jump back to the star of loop return fact; // Return the result } // factorial() ends here } // The class ends here From Java in a Nutshell
  • 13. UMBC CMSC 331 Java JAVA Classes • The class is the fundamental concept in JAVA (and other OOPLs) • A class describes some data object(s), and the operations (or methods) that can be applied to those objects • Every object and method in Java belongs to a class • Classes have data (fields) and code (methods) and classes (member classes or inner classes) • Static methods and fields belong to the class itself • Others belong to instances
  • 14. UMBC CMSC 331 Java Example public class Circle { // A class field public static final double PI= 3.14159; // A useful constant // A class method: just compute a value based on the arguments public static double radiansToDegrees(double rads) { return rads * 180 / PI; } // An instance field public double r; // The radius of the circle // Two methods which operate on the instance fields of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference of the circle return 2 * PI * r; } }
  • 15. UMBC CMSC 331 Java Constructors • Classes should define one or more methods to create or construct instances of the class • Their name is the same as the class name – note deviation from convention that methods begin with lower case • Constructors are differentiated by the number and types of their arguments – An example of overloading • If you don’t define a constructor, a default one will be created. • Constructors automatically invoke the zero argument constructor of their superclass when they begin (note that this yields a recursive process!)
  • 16. UMBC CMSC 331 Java Constructor example public class Circle { public static final double PI = 3.14159; // A constant public double r; // instance field holds circle’s radius // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } // Constructor to use if no arguments public Circle() { r = 1.0; } // better: public Circle() { this(1.0); } // The instance methods: compute values based on radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } } this.r refers to the r field of the class This() refers to a constructor for the class
  • 17. UMBC CMSC 331 Java Extending a class • Class hierarchies reflect subclass-superclass relations among classes. • One arranges classes in hierarchies: – A class inherits instance variables and instance methods from all of its superclasses. Tree -> BinaryTree -> BST – You can specify only ONE superclass for any class. • When a subclass-superclass chain contains multiple instance methods with the same signature (name, arity, and argument types), the one closest to the target instance in the subclass- superclass chain is the one executed. – All others are shadowed/overridden. • Something like multiple inheritance can be done via interfaces (more on this later) • What’s the superclass of a class defined without an extends clause?
  • 18. UMBC CMSC 331 Java Extending a class public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle, // so we only have to put the new stuff here. // New instance fields that store the center point of the circle public double cx, cy; // A new constructor method to initialize the new fields // It uses a special syntax to invoke the Circle() constructor public PlaneCircle(double r, double x, double y) { super(r); // Invoke the constructor of the superclass, Circle() this.cx = x; // Initialize the instance field cx this.cy = y; // Initialize the instance field cy } // The area() and circumference() methods are inherited from Circle // A new instance method that checks whether a point is inside the circle // Note that it uses the inherited instance field r public boolean isInside(double x, double y) { double dx = x - cx, dy = y - cy; // Distance from center double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem return (distance < r); // Returns true or false } }
  • 19. UMBC CMSC 331 Java Overloading, overwriting, and shadowing • Overloading occurs when Java can distinguish two procedures with the same name by examining the number or types of their parameters. • Shadowing or overriding occurs when two procedures with the same signature (name, the same number of parameters, and the same parameter types) are defined in different classes, one of which is a superclass of the other.
  • 20. UMBC CMSC 331 Java On designing class hierarchies • Programs should obey the explicit-representation principle, with classes included to reflect natural categories. • Programs should obey the no-duplication principle, with instance methods situated among class definitions to facilitate sharing. • Programs should obey the look-it-up principle, with class definitions including instance variables for stable, frequently requested information. • Programs should obey the need-to-know principle, with public interfaces designed to restrict instance-variable and instance-method access, thus facilitating the improvement and maintenance of nonpublic program elements. • If you find yourself using the phrase an X is a Y when describing the relation between two classes, then the X class is a subclass of the Y class. • If you find yourself using X has a Y when describing the relation between two classes, then instances of the Y class appear as parts of instances of the X class.
  • 21. UMBC CMSC 331 Java Data hiding and encapsulation • Data-hiding or encapsulation is an important part of the OO paradigm. • Classes should carefully control access to their data and methods in order to – Hide the irrelevant implementation-level details so they can be easily changed – Protect the class against accidental or malicious damage. – Keep the externally visible class simple and easy to document • Java has a simple access control mechanism to help with encapsulation – Modifiers: public, protected, private, and package (default)
  • 22. UMBC CMSC 331 Java Example encapsulation package shapes; // Specify a package for the class public class Circle { // The class is still public public static final double PI = 3.14159; protected double r; // Radius is hidden, but visible to subclasses // A method to enforce the restriction on the radius // This is an implementation detail that may be of interest to subclasses protected checkRadius(double radius) { if (radius < 0.0) throw new IllegalArgumentException("radius may not be negative."); } // The constructor method public Circle(double r) {checkRadius(r); this.r = r; } // Public data accessor methods public double getRadius() { return r; }; public void setRadius(double r) { checkRadius(r); this.r = r;} // Methods to operate on the instance field public double area() { return PI * r * r; } public double circumference() { return 2 * PI * r; } }
  • 23. UMBC CMSC 331 Java Access control • Access to packages – Java offers no control mechanisms for packages. – If you can find and read the package you can access it • Access to classes – All top level classes in package P are accessible anywhere in P – All public top-level classes in P are accessible anywhere • Access to class members (in class C in package P) – Public: accessible anywhere C is accessible – Protected: accessible in P and to any of C’s subclasses – Private: only accessible within class C – Package: only accessible in P (the default)
  • 25. UMBC CMSC 331 Java Getters and setters • A getter is a method that extracts information from an instance. – One benefit: you can include additional computation in a getter. • A setter is a method that inserts information into an instance (also known as mutators). – A setter method can check the validity of the new value (e.g., between 1 and 7) or trigger a side effect (e.g., update a display) • Getters and setters can be used even without underlying matching variables • Considered good OO practice • Essential to javabeans • Convention: for variable fooBar of type fbtype, define – getFooBar() – setFooBar(fbtype x)
  • 26. UMBC CMSC 331 Java Example getters and setters package shapes; // Specify a package for the class public class Circle { // The class is still public // This is a generally useful constant, so we keep it public public static final double PI = 3.14159; protected double r; // Radius is hidden, but visible to subclasses // A method to enforce the restriction on the radius // This is an implementation detail that may be of interest to subclasses protected checkRadius(double radius) { if (radius < 0.0) throw new IllegalArgumentException("radius may not be negative."); } // The constructor method public Circle(double r) { checkRadius(r); this.r = r;} // Public data accessor methods public double getRadius() { return r; }; public void setRadius(double r) { checkRadius(r); this.r = r;} // Methods to operate on the instance field public double area() { return PI * r * r; } public double circumference() { return 2 * PI * r; } }
  • 27. UMBC CMSC 331 Java Abstract classes and methods • Abstract vs. concrete classes • Abstract classes can not be instantiated public abstract class shape { } • An abstract method is a method w/o a body public abstract double area(); • (Only) Abstract classes can have abstract methods • In fact, any class with an abstract method is automatically an abstract class
  • 28. UMBC CMSC 331 Java Example abstract class public abstract class Shape { public abstract double area(); // Abstract methods: note public abstract double circumference();// semicolon instead of body. } class Circle extends Shape { public static final double PI = 3.14159265358979323846; protected double r; // Instance data public Circle(double r) { this.r = r; } // Constructor public double getRadius() { return r; } // Accessor public double area() { return PI*r*r; } // Implementations of public double circumference() { return 2*PI*r; } // abstract methods. } class Rectangle extends Shape { protected double w, h; // Instance data public Rectangle(double w, double h) { // Constructor this.w = w; this.h = h; } public double getWidth() { return w; } // Accessor method public double getHeight() { return h; } // Another accessor public double area() { return w*h; } // Implementations of public double circumference() { return 2*(w + h); } // abstract methods. }
  • 29. UMBC CMSC 331 Java Syntax Notes • No global variables – class variables and methods may be applied to any instance of an object – methods may have local (private?) variables • No pointers – but complex data objects are “referenced” • Other parts of Java are borrowed from PL/I, Modula, and other languages