How To Use Constructor in Java Programming Language
The Following script is the simplest way to declaring and using constructor in Java programming language:
Class diagram:
Java program:
//Titik = point = dot = pixel
//Titik3D = 3DPoint
class Titik{
private int X;
private int Y;
Titik(){
}
Titik(int X, int Y){
setX(X);
setY(Y);
}
protected void setX(int X){
this.X = X;
}
public int getX(){
return X;
}
protected void setY(int Y){
this.Y = Y;
}
public int getY(){
return Y;
}
}
class Titik3D extends Titik{ //Titik3D = 3DPoint
private int Z;
Titik3D(){
}
Titik3D(int X, int Y, int Z){
setX(X);
setY(Y);
setZ(Z);
}
protected void setZ(int Z){
this.Z = Z;
}
public int getZ(){
return Z;
}
}
class DemoConstructor{
public static void main(String args[]){
Titik T2D = new Titik(10,20);
Titik3D T3D = new Titik3D(10,20,30);
System.out.println("Titik 2D ("+ T2D.getX() +","+ T2D.getY() +")");
System.out.println("Titik 3D ("+ T3D.getX() +","+ T3D.getY() +","+ T3D.getZ() +")");
}
}
Output:
ShadowOfBdg© - All rights reserved.
No comments:
Post a Comment