The document provides an overview of Java basics including comments, classes, methods, constructors, arrays, scoping, and more. It discusses:
1) How comments work in Java and how javadoc comments generate API documentation.
2) The basics of classes including defining a simple Person class with fields and methods.
3) How scoping works similarly to C/C++ with curly braces and how variables are not redeclared within the same scope.
4) That arrays are objects that are dynamically allocated and subject to garbage collection in Java.
Lara Technologies are providing Software Training Division, Java/J2ee, Android, Web Services, Logical Coding, Basics Of C Language, Soft Skills, Aptitude, Etc.
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
Method and Method overloading
How to overload method in JAVA?
Method overloading Examples of the program.
New operator
Recursion
Passing and returning objects from methods.
Class object method constructors in javaRaja Sekhar
Presented By :
N.V.Raja Sekhar Reddy
www.technolamp.co.in
www.programming9.com
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
Java OOP Programming language (Part 3) - Class and Object
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
Lara Technologies are providing Software Training Division, Java/J2ee, Android, Web Services, Logical Coding, Basics Of C Language, Soft Skills, Aptitude, Etc.
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
Method and Method overloading
How to overload method in JAVA?
Method overloading Examples of the program.
New operator
Recursion
Passing and returning objects from methods.
Class object method constructors in javaRaja Sekhar
Presented By :
N.V.Raja Sekhar Reddy
www.technolamp.co.in
www.programming9.com
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
Java OOP Programming language (Part 3) - Class and Object
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
Идея создания аниме магазина,в котором будут продаваться аниме товары:фигурки,кружки,бейсболки,футболки с аниме,манги,манхва,конечно же само аниме и аниме игры и все для косплея
Туристический портал – «Афиша Подмосковья» – это наиболее полный и целостный каталог культурно-исторических объектов, музеев, усадеб, храмов и монастырей, театров, туристических и досуговых центров, спортивных комплексов, центров народных художественных промыслов и т.д. Кроме того – это интерактивный сервис, фотографии, карты, пользовательские рейтинги, новости культурной и спортивной жизни Подмосковья, заметки, отзывы, интервью с известными людьми и многое другое.
Myassignmenthelpers.com is an Online service provider for Java assignments & homework problems. Our online experts provide Java Assignment help & Java homework help with aims to help college students across the globe. Our writers provide you unique data along with a plagiarised report so that you can ensure that your data is unique. Our writers are available 24*7. Please send your complete requirements at support@myassignmenthelpers.com or else attach on the website. You can also discuss the requirements with our chat agent.
Core java training in Bangalore is one the best Training in Entire bangalore, Where you can learn Java in Shorter time. TIB Academy is the platform where you gain all you confidence back.
Detailed presentation on Inheritance and interfaces in JAVA. Presentation includes suitable example for better understanding the concepts such as Overriding in java and also keywords such as FINAL and SUPER.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
2. UMBC CMSC 331 Java
Comments are almost like C++Comments are almost like C++
The javadoc program generates HTML API
documentation from the “javadoc” style
comments in your code.
2
/* 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 classAn example of a class
3
class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name +
' is now ' + age);
}
}
Variable
Method
4. UMBC CMSC 331 Java
ScopingScoping
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.
4
{ 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 objectAn 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!
5
6. UMBC CMSC 331 Java
Scope of ObjectsScope 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"); 6
7. UMBC CMSC 331 Java
Methods, arguments and return valuesMethods, 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() {}
7
8. UMBC CMSC 331 Java
The static keywordThe 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
8
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 OperationsArray 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
9
11. Echo.javaEcho.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 ExampleFactorial 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 12
From Java in a Nutshell
13. UMBC CMSC 331 Java
JAVA ClassesJAVA 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
13
14. UMBC CMSC 331 Java
ExampleExample
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;
}
}
14
15. UMBC CMSC 331 Java
ConstructorsConstructors
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!)
15
16. UMBC CMSC 331 Java
Constructor exampleConstructor 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; }
}
16
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 classExtending 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?
17
18. UMBC CMSC 331 Java
Extending a classExtending 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 18
19. UMBC CMSC 331 Java
Overloading, overwriting, and shadowingOverloading, 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.
19
20. UMBC CMSC 331 Java
On designing class hierarchiesOn 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 aY when describing the
relation between two classes, then the X class is a subclass of theY class.
If you find yourself using X has aY when describing the relation between
two classes, then instances of theY class appear as parts of instances of
the X class.
20
21. UMBC CMSC 331 Java
Data hiding and encapsulationData 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 21
22. UMBC CMSC 331 Java
ExampleExample
encapsulationencapsulation
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; }
}
22
23. UMBC CMSC 331 Java
Access controlAccess 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 23
25. UMBC CMSC 331 Java
Getters and settersGetters 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)
25
26. UMBC CMSC 331 Java
ExampleExample
getters and settersgetters 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; }
26
27. UMBC CMSC 331 Java
Abstract classes and methodsAbstract 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 27
28. UMBC CMSC 331 Java
ExampleExample
abstract classabstract 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. 28
29. UMBC CMSC 331 Java
Syntax NotesSyntax 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
29