Você está na página 1de 7

Java Programs on Classes & Objects

/* Default Initialization of Class Fields. - DefaultInit.java

*/

class DefaultInit {
byte b;
short s;
int i;
long l;
float f;
double d;
boolean bool;
String str;
public static void main(String[] args) {
// Create an object of DefaultInit class
DefaultInit obj = new DefaultInit();
// Print the default values for all instance variables
System.out.println("byte is initialized to " + obj.l);
System.out.println("short is initialized to " + obj.s);
System.out.println("int is initialized to " + obj.i);
System.out.println("long is initialized to " + obj.l);
System.out.println("float is initialized to " + obj.f);
System.out.println("double is initialized to " + obj.d);
System.out.println("boolean is initialized to " + obj.bool);
System.out.println("String is initialized to " + obj.str);
}
}
/*
byte is initialized to 0
short is initialized to 0
int is initialized to 0
long is initialized to 0
float is initialized to 0.0
double is initialized to 0.0
boolean is initialized to false
String is initialized to null
*/

/* Declaration of a Human Class with One Class Variable and Two Instance Variables. Human.java
*/
public class
String
String
static
}

Human {
name;
gender;
long count;

// Instance variable
// Instance variable
// Class variable

/* A Test Class to Demonstrate How to Access (Read/Write) Class Variables and


Instance Variables of a Class. - FieldAccessTest.java */
class FieldAccessTest {
public static void main(String[] args) {
// Create an instance of Human class
Human jack = new Human();
// Increase count by one
Human.count++;
// Assign values to name and gender
jack.name = "Jack Parker";
jack.gender = "Male";
// Read and print the values of name, gender and count
String jackName = jack.name;
String jackGender = jack.gender;
long population = Human.count;
System.out.println("Name: " + jackName);
System.out.println("Gender: " + jackGender);
System.out.println("Population: " + population);
// Change the name
jack.name = "Jackie Parker";
// Read and print the changed name
String changedName = jack.name;
System.out.println("Changed Name: " + changedName);
}
}
/*
Name: Jack Parker
Gender: Male
Population: 1
Changed Name: Jackie Parker
*/
1

Java Programs on Classes & Objects

// A simple example of recursion. Recursion.java


class Factorial {
// this is a recusive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
/*
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
*/

// This program uses a parameterized method. - BoxDemo5.java


class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
/*
Volume is 3000.0
Volume is 162.0
*/

/* Here, Box uses a constructor to initialize the dimensions of a box. BoxDemo6.java */


class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
2

Java Programs on Classes & Objects


// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
/*
Volume is 1000.0
Volume is 1000.0
*/

// Demonstrate method overloading. - Overload.java


class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
/*
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
*/

// Automatic type conversions apply to overloading. - OverloadTc.java


class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter and return type
void test(double a) {
3

Java Programs on Classes & Objects


System.out.println("Inside test(double) a: " + a);
}
}
class OverloadTc {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
/*
No parameters
a and b: 10 20
Inside test(double) a: 88.0
Inside test(double) a: 123.2
*/

/* Here, Box defines three constructors to initialize the dimensions of a box various
ways. - OverloadCons.java
*/
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
/*
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
*/

// Demonstrate static variables, methods, and blocks. UseStatic.java


class UseStatic {
static int a = 3;
4

Java Programs on Classes & Objects


static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
/*
Static block initialized.
x = 42
a = 3
b = 12
*/

// Demonstrate static variables and methods 2. StaticByName.java


class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
/*
a = 42
b = 99
*/

// Demonstrate static variables and methods 3. StaticMethod.java


import java.util.Scanner;
class StaticMethod{
static void area(int x,int y, int z){
int sarea=(2*x*y)+(2*y*z)+(2*z*x);
System.out.println("surface area=" + sarea );
}
static void volume(int x,int y, int z){
System.out.println("volume= "+x*y*z);
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int width;
int height;
int depth;
int vol;
System.out.println("Enter three int dimensions of box");
width=in.nextInt();
height=in.nextInt();
depth=in.nextInt();
area(width,height,depth);
volume(width,height,depth);
}
}
/*
Enter three int dimensions of box
3
4
5
surface area=94
volume= 60
*/

/* Accessing Class Fields from Static and Non-static Methods. Examples of Invoking
Instance Methods and Class Methods of a Class. - MethodType.java */
public class MethodType {
5

Java Programs on Classes & Objects


static int m = 100; // A static variable
int n = 200;
// An instance variable
// Declare a static method
static void printM() {
/* We can refer to only static variable m in this method because we are inside a
static method */
System.out.println("printM() - m = " + m);
/* System.out.println("printM() - n = " + n); */ /* A Compiler error */
}
// Declare an instance method
void printMN() {
/* We can refer to both static and instance variables m and n in this method */
System.out.println("printMN() - m = " + m);
System.out.println("printMN() - n = " + n);
}
}

// MethodTypeTest.java
public class MethodTypeTest {
public static void main(String[] args) {
// Create an instance of the MethodTYpe class
MethodType mt = new MethodType();
System.out.println("Invoking instance method...");
// Invoke the instance method
mt.printMN();
System.out.println("Invoking class method on class name...");
// Invoke the class method using the class name
MethodType.printM();
System.out.println("Invoking class method on an instance...");
// Invoke the class method using the instance reference
mt.printM();
}
}/*
Invoking instance method...
printMN() - m = 100
printMN() - n = 200
Invoking class method on class name...
printM() - m = 100
Invoking class method on an instance...
printM() - m = 100
*/

/* Can you invoke the main() method in your code?


a main() Method. - MainTest1.java.
*/

A MainTest1 Class, Which Declares

public class MainTest1 {


public static void main(String[] args) {
System.out.println("Inside main() method of the MainTest1 class.");
}
}

/* A MainTest2 Class, Which Declares a main( ) Method, Which in Turn Calls the main()
Method of the MainTest1 Class - MainTest2.java */
public class MainTest2 {
public static void main(String[] args) {
MainTest1.main(args);
}
}
// run MainTest2
/* Inside main() method of the MainTest1 class */
Or
// run MainTest1
/* Inside main() method of the MainTest1 class */
---------------------------------------------------------------------------------------------

// This C Program defines an integer stack


that can hold 10 values.
#include<stdio.h>
#define MAX 10
struct stack {
int stck[MAX];
int tos;
};
// Initialize top-of-stack
void initialize( struct stack *s) {
s->tos = -1;

}
// Push an item onto the stack
void push(struct stack *s, int item) {
if(s->tos==MAX-1)
printf("Stack is full.\n");
else
s->stck[++s->tos] = item;
}
// Pop an item from the stack
int pop(struct stack *s) {
6

Java Programs on Classes & Objects


if(s->tos < 0) {
printf("Stack underflow.\n");
return 0;
}
else
return s->stck[s->tos--];
}
void main() {
struct stack *mystack1, *mystack2;
mystack1 = malloc(sizeof(struct stack));
mystack2 = malloc(sizeof(struct stack));
initialize(mystack1);
initialize(mystack2);
// push some numbers onto the stack
for(int i=0; i<10; i++) push(mystack1, i);
for(int i=10; i<20; i++) push(mystack2, i);
// pop those numbers off the stack
printf("Stack in mystack1:\n");
for(int i=0; i<10; i++)
printf("%d\n", pop(mystack1));
printf("Stack in mystack2:\n");
for(int i=0; i<10; i++)
printf("%d\n",pop(mystack2));
}
/*
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
*/

// This Java class defines an integer


stack that can hold 10 values.
class Stack {
int stck[] = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}

}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
/*
C:\java-class-programs>javac TestStack.java
C:\java-class-programs>java TestStack
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
*/

// StringLength.java
public class StringLength {
public static void main (String[] args) {
// Create two string objects
String str1 = new String() ;
String str2 = new String("Hello") ;
// Get the length of str1 and str2
int len1 = str1.length();
int len2 = str2.length();
// Display the length of str1 and str2
System.out.println("Length of \"" +
str1 + "\" = " + len1);
System.out.println("Length of \"" +
str2 + "\" = " + len2);
}
}
/*
C:\java-class-programs>javac StringLength.java
C:\java-class-programs>java StringLength
Length of "" = 0
Length of "Hello" = 5
*/

Você também pode gostar